Class: Goldiloader::AutoIncludeContext

Inherits:
Object
  • Object
show all
Includes:
CustomPreloads
Defined in:
lib/goldiloader/auto_include_context.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CustomPreloads

#preloaded

Constructor Details

#initializeAutoIncludeContext

Returns a new instance of AutoIncludeContext.



9
10
11
# File 'lib/goldiloader/auto_include_context.rb', line 9

def initialize
  @models = []
end

Instance Attribute Details

#modelsObject (readonly)

Returns the value of attribute models.



5
6
7
# File 'lib/goldiloader/auto_include_context.rb', line 5

def models
  @models
end

Class Method Details

.register_models(models, included_associations = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/goldiloader/auto_include_context.rb', line 13

def self.register_models(models, included_associations = nil)
  auto_include_context = Goldiloader::AutoIncludeContext.new
  auto_include_context.register_models(models)

  Array.wrap(included_associations).each do |included_association|
    associations = if included_association.is_a?(Hash)
                     included_association.keys
                   else
                     Array.wrap(included_association)
                   end
    nested_associations = if included_association.is_a?(Hash)
                            included_association
                          else
                            Hash.new([])
                          end

    associations.each do |association|
      nested_models = models.flat_map do |model|
        model.association(association).target
      end.compact

      register_models(nested_models, nested_associations[association])
    end
  end
end

Instance Method Details

#register_models(models) ⇒ Object Also known as: register_model



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/goldiloader/auto_include_context.rb', line 39

def register_models(models)
  # Don't use Array() or Array.wrap() because they will check respond_to?(:to_ary)
  # which for ActiveStorage::Attachment will delegate to the blob association which
  # triggers an infinite eager loading loop on the association
  models = [models] unless models.is_a?(Array)
  models.each do |model|
    next if model.nil?

    model.auto_include_context = self
    self.models << model
  end
  self
end