Module: BatchLoaderActiveRecord::ClassMethods

Defined in:
lib/batch_loader_active_record.rb

Instance Method Summary collapse

Instance Method Details

#association_accessor(name) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/batch_loader_active_record.rb', line 13

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
  when :has_and_belongs_to_many
    define_method(manager.accessor_name) do |instance_scope = nil|
      manager.has_and_belongs_to_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



34
35
36
37
38
39
# File 'lib/batch_loader_active_record.rb', line 34

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_and_belongs_to_many_lazy(*args) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/batch_loader_active_record.rb', line 57

def has_and_belongs_to_many_lazy(*args)
  has_and_belongs_to_many(*args).tap do |reflections|
    manager = AssociationManager.new(model: self, reflection: reflect_on_all_associations.last)
    define_method(manager.accessor_name) do |instance_scope = nil|
      manager.has_and_belongs_to_many_to_batch_loader(self, instance_scope)
    end
  end
end

#has_many_lazy(*args) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/batch_loader_active_record.rb', line 48

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



41
42
43
44
45
46
# File 'lib/batch_loader_active_record.rb', line 41

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