Module: BatchLoaderActiveRecord::ClassMethods

Defined in:
lib/batch_loader_active_record.rb

Instance Method Summary collapse

Instance Method Details

#association_accessor(name) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/batch_loader_active_record.rb', line 20

def association_accessor(name)
  reflection = reflect_on_association(name) or raise "Can't find association #{name.inspect}"
  manager = AssociationManager.new(model: self, reflection: reflection)
  case reflection.macro
  when :belongs_to
    define_method(manager.accessor_name) { manager.belongs_to_batch_loader(self) }
  when :has_one
    define_method(manager.accessor_name) { manager.has_one_to_batch_loader(self) }
  when :has_many
    define_method(manager.accessor_name) do |instance_scope = nil|
      manager.has_many_to_batch_loader(self, instance_scope)
    end
  else
    raise NotImplementedError, "association kind #{reflection.macro.inspect} is not yet supported"
  end
end

#belongs_to_lazy(*args) ⇒ Object



13
14
15
16
17
18
# File 'lib/batch_loader_active_record.rb', line 13

def belongs_to_lazy(*args)
  belongs_to(*args).tap do |reflections|
    manager = AssociationManager.new(model: self, reflection: reflections.values.last)
    define_method(manager.accessor_name) { manager.belongs_to_batch_loader(self) }
  end
end

#has_many_lazy(*args) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/batch_loader_active_record.rb', line 44

def has_many_lazy(*args)
  has_many(*args).tap do |reflections|
    manager = AssociationManager.new(model: self, reflection: reflections.values.last)
    define_method(manager.accessor_name) do |instance_scope = nil|
      manager.has_many_to_batch_loader(self, instance_scope)
    end
  end
end

#has_one_lazy(*args) ⇒ Object



37
38
39
40
41
42
# File 'lib/batch_loader_active_record.rb', line 37

def has_one_lazy(*args)
  has_one(*args).tap do |reflections|
    manager = AssociationManager.new(model: self, reflection: reflections.values.last)
    define_method(manager.accessor_name) { manager.has_one_to_batch_loader(self) }
  end
end