class ArLazyPreload::AssociatedContextBuilder

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.

Attributes

association_name[R]
parent_context[R]

Public Class Methods

new(parent_context:, association_name:) click to toggle source

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

# 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
prepare(**args) click to toggle source

Initiates lazy preload context the records loaded lazily

# File lib/ar_lazy_preload/associated_context_builder.rb, line 11
def self.prepare(**args)
  new(**args).perform
end

Public Instance Methods

perform() click to toggle source

Takes all the associated records for the records, attached to the :parent_context and creates a preloading context for them rubocop:disable Metrics/MethodLength, Metrics/AbcSize

# File lib/ar_lazy_preload/associated_context_builder.rb, line 27
def perform
  associated_records = parent_context.records.flat_map do |record|
    next if record.nil?

    reflection = reflection_cache[record.class]
    next if reflection.nil?

    record_association = record.association(association_name)
    reflection.collection? ? record_association.target : record_association.reader
  end

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

Private Instance Methods

child_association_tree() click to toggle source

rubocop:enable Metrics/MethodLength, Metrics/AbcSize

# File lib/ar_lazy_preload/associated_context_builder.rb, line 48
def child_association_tree
  # `association_tree` is unnecessary when auto preload is enabled
  return nil if parent_context.auto_preload?

  AssociationTreeBuilder.new(parent_context.association_tree).subtree_for(association_name)
end
reflection_cache() click to toggle source
# File lib/ar_lazy_preload/associated_context_builder.rb, line 55
def reflection_cache
  @reflection_cache ||= Hash.new do |hash, klass|
    hash[klass] = klass.reflect_on_association(association_name)
  end
end