Module: AmsLazyRelationships::Core::LazyRelationshipMethod

Included in:
ClassMethods
Defined in:
lib/ams_lazy_relationships/core/lazy_relationship_method.rb

Instance Method Summary collapse

Instance Method Details

#lazy_relationship(name, loader: nil, load_for: nil) ⇒ Object

This method defines a new lazy relationship on the serializer and a method with ‘lazy_` prefix.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ams_lazy_relationships/core/lazy_relationship_method.rb', line 23

def lazy_relationship(name, loader: nil, load_for: nil)
  @lazy_relationships ||= {}

  name = name.to_sym

  loader ||= begin
    current_model_class = self.name.demodulize.gsub("Serializer", "")
    AmsLazyRelationships::Loaders::Association.new(current_model_class, name)
  end

  lrm = LazyRelationshipMeta.new(
    name: name,
    loader: loader,
    reflection: find_reflection(name),
    load_for: load_for
  )
  @lazy_relationships[name] = lrm

  define_method :"lazy_#{name}" do
    self.class.send(:load_lazy_relationship, name, object)
  end
end