Class: Prelude::Preloader

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

Instance Method Summary collapse

Constructor Details

#initialize(klass, records) ⇒ Preloader

Returns a new instance of Preloader.



3
4
5
6
7
# File 'lib/prelude/preloader.rb', line 3

def initialize(klass, records)
  @klass = klass
  @records = records
  @runs = {}
end

Instance Method Details

#fetch(name, object, *args) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/prelude/preloader.rb', line 9

def fetch(name, object, *args)
  method = @klass.prelude_methods.fetch(name)

  # If this object has a run, return the value
  if run = run_for(method, args, object)
    return run[object]
  end

  # Choose a batch of the correct size that contains the object we're trying to load,
  # or use all if we're not batching
  run = if method.batch_size
    remaining_records = @records.to_a - resolved_objects_for(method, args)
    slices = remaining_records.each_slice(method.batch_size)
    slice = slices.detect { |slice| slice.include?(object) }
    preload(method, slice, args)
  else
    preload(method, @records, args)
  end

  # Return the value for this object
  run[object]
end