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.

Parameters:

  • name (Symbol)

    The name of the lazy relationship. It’ll be used to define lazy_ method.

  • loader (Object) (defaults to: nil)

    An object responding to ‘load(record)` method. By default the AR association loader is used. The loader should either lazy load (e.g. use BatchLoader) the data or perform a very light action, because it might be called more than once when serializing the data.

  • load_for (Symbol) (defaults to: nil)

    Optionally you can delegate the loading to a method defined by ‘load_for` symbol. It is useful e.g. when the loaded object is a decorated object and the real AR model is accessible by calling the decorator’s method.



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