Class: ArLazyPreload::AssociatedContextBuilder

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

Overview

This class is responsible for building context for associated records. Given a list of records belonging to the same context and association name it will create and attach a new context to the associated records based on the parent association tree.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent_context:, association_name:) ⇒ AssociatedContextBuilder

:parent_context - root context :association_name - lazily preloaded association name



19
20
21
22
# File 'lib/ar_lazy_preload/associated_context_builder.rb', line 19

def initialize(parent_context:, association_name:)
  @parent_context = parent_context
  @association_name = association_name
end

Instance Attribute Details

#association_nameObject (readonly)

Returns the value of attribute association_name.



15
16
17
# File 'lib/ar_lazy_preload/associated_context_builder.rb', line 15

def association_name
  @association_name
end

#parent_contextObject (readonly)

Returns the value of attribute parent_context.



15
16
17
# File 'lib/ar_lazy_preload/associated_context_builder.rb', line 15

def parent_context
  @parent_context
end

Class Method Details

.prepare(*args) ⇒ Object

Initiates lazy preload context the records loaded lazily



11
12
13
# File 'lib/ar_lazy_preload/associated_context_builder.rb', line 11

def self.prepare(*args)
  new(*args).perform
end

Instance Method Details

#performObject

Takes all the associated records for the records, attached to the :parent_context and creates a preloading context for them



26
27
28
29
30
31
32
33
34
# File 'lib/ar_lazy_preload/associated_context_builder.rb', line 26

def perform
  records_by_class = parent_context.records.group_by(&:class)

  associated_records = records_by_class.map do |klass, klass_records|
    associated_records_for(klass, klass_records)
  end.flatten

  Context.register(records: associated_records, association_tree: child_association_tree)
end