Class: SmartPreloads::Loader

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, nested_associations = nil) ⇒ Loader

Returns a new instance of Loader.



5
6
7
8
# File 'lib/smart_preloads/loader.rb', line 5

def initialize(collection, nested_associations = nil)
  @collection = collection
  @nested_associations = nested_associations
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



3
4
5
# File 'lib/smart_preloads/loader.rb', line 3

def collection
  @collection
end

Instance Method Details

#load(association) ⇒ Object



14
15
16
17
18
# File 'lib/smart_preloads/loader.rb', line 14

def load(association)
  association = nest(association)
  return unless association
  ActiveRecord::Associations::Preloader.new.preload(@collection, association)
end

#load_defaultObject



10
11
12
# File 'lib/smart_preloads/loader.rb', line 10

def load_default
  load(nil)
end

#nest(association) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/smart_preloads/loader.rb', line 25

def nest(association)
  return association unless @nested_associations
  result = association
  Array(@nested_associations).reverse.each do |parent|
    if result
      result = { parent => result }
    else
      result = parent
    end
  end
  result
end

#nested(nested_associations) ⇒ Object



20
21
22
23
# File 'lib/smart_preloads/loader.rb', line 20

def nested(nested_associations)
  self.class.new(@collection, Array(@nested_associations) +
                              Array(nested_associations))
end