Class: ArLazyPreload::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/ar_lazy_preload/context.rb

Overview

This class is responsible for holding a connection between a list of ActiveRecord::Base objects which have been loaded by the same instance of ActiveRecord::Relation. It also contains a tree of associations, which were requested to be loaded lazily. Calling #preload_association method will cause loading of ALL associated objects for EACH ecord when requested association is found in the association tree.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, records:, association_tree:) ⇒ Context

:model - ActiveRecord class which records belong to :records - array of ActiveRecord instances :association_tree - list of symbols or hashes representing a tree of preloadable associations



17
18
19
20
21
22
23
# File 'lib/ar_lazy_preload/context.rb', line 17

def initialize(model:, records:, association_tree:)
  @model = model
  @records = records.compact
  @association_tree = association_tree

  @records.each { |record| record.lazy_preload_context = self }
end

Instance Attribute Details

#association_treeObject (readonly)

Returns the value of attribute association_tree.



12
13
14
# File 'lib/ar_lazy_preload/context.rb', line 12

def association_tree
  @association_tree
end

#modelObject (readonly)

Returns the value of attribute model.



12
13
14
# File 'lib/ar_lazy_preload/context.rb', line 12

def model
  @model
end

#recordsObject (readonly)

Returns the value of attribute records.



12
13
14
# File 'lib/ar_lazy_preload/context.rb', line 12

def records
  @records
end

Instance Method Details

#try_preload_lazily(association_name) ⇒ Object

This method checks if the association is present in the association_tree and preloads for all objects in the context it if needed.



27
28
29
30
31
32
33
34
35
36
# File 'lib/ar_lazy_preload/context.rb', line 27

def try_preload_lazily(association_name)
  return unless association_needs_preload?(association_name)

  preloader.preload(records, association_name)

  AssociatedContextBuilder.new(
    parent_context: self,
    association_name: association_name
  ).perform
end