Class: StrictLazy::Batch

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

Overview

A single StrictLazy.preload × single loader unit of work, shared by every record in the group via @batch<reader>. The resolver runs exactly once; values are written straight onto each record’s @lazy<reader> ivar, so the batch keeps no intermediate Hash and never relies on record hash-equality (unsaved records work fine).

Instance Method Summary collapse

Constructor Details

#initialize(model, records, loader) ⇒ Batch

Returns a new instance of Batch.



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

def initialize(model, records, loader)
  @model = model
  @records = records
  @loader = loader
  @resolved = false
end

Instance Method Details

#resolve!Object

Run the resolver once and write defaults for any record it skipped.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/strict_lazy/batch.rb', line 24

def resolve!
  return if @resolved

  @resolved = true
  fulfilled = {}.compare_by_identity
  fulfill = lambda do |record, value|
    fulfilled[record] = true
    record.instance_variable_set(@loader.value_ivar, value)
  end

  @loader.resolve(@model, @records, fulfill)

  @records.each do |record|
    next if fulfilled.key?(record)

    record.instance_variable_set(@loader.value_ivar, @loader.default_for(record))
  end
end

#value_for(record) ⇒ Object

Resolve the value for one record, resolving the whole group on first touch.



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

def value_for(record)
  resolve! unless @resolved
  record.instance_variable_get(@loader.value_ivar)
end