Class: StrictLazy::Preloader

Inherits:
Object
  • Object
show all
Defined in:
lib/strict_lazy/preloader.rb

Overview

Drives StrictLazy.preload: interprets the Rails-style spec, prepares each level’s readers (grouped by STI base class), and traverses associations to descend into nested records. One instance handles a single level of records; nested levels are handled by recursing into fresh instances.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(records) ⇒ Preloader

Returns a new instance of Preloader.



18
19
20
# File 'lib/strict_lazy/preloader.rb', line 18

def initialize(records)
  @records = records
end

Class Method Details

.call(records, spec) ⇒ Object

Prepare spec on records. See StrictLazy.preload for the spec grammar.



10
11
12
13
14
15
16
# File 'lib/strict_lazy/preloader.rb', line 10

def self.call(records, spec)
  records = Array(records)
  return records if records.empty?

  new(records).call(spec)
  records
end

Instance Method Details

#call(spec) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/strict_lazy/preloader.rb', line 22

def call(spec)
  hashes, readers = spec.partition { |element| element.is_a?(Hash) }

  preload_here(readers) if prepare_this_level?(spec, readers)

  hashes.flat_map(&:to_a).each do |association, sub_spec|
    children = traverse(association)
    # Array.wrap (not Kernel#Array) so a Hash sub-spec stays a single element
    # ([hash]) instead of being split into key/value pairs.
    self.class.call(children, Array.wrap(sub_spec))
  end
end