Class: SmartPreloads::Item

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/smart_preloads/item.rb

Instance Method Summary collapse

Constructor Details

#initialize(record, loader: nil) ⇒ Item

Returns a new instance of Item.



3
4
5
6
7
# File 'lib/smart_preloads/item.rb', line 3

def initialize(record, loader: nil)
  super(record)
  @loader = loader || Loader.new([record])
  _override_associations
end

Instance Method Details

#_override_associationsObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/smart_preloads/item.rb', line 9

def _override_associations
  __getobj__.class.reflections.each do |key, association|
    body = nil
    loader = @loader
    if %i(has_many has_and_belongs_to_many).include?(association.macro)
      body = lambda do
        List.new(super(), loader: loader.nested(key.to_sym))
      end
    else
      body = lambda do
        loader.load(key.to_sym)
        super()
      end
    end
    __getobj__.define_singleton_method(key, &body)
  end
end