Class: N1Loader::Preloader

Inherits:
Object
  • Object
show all
Includes:
ArLazyPreload::PreloaderPatch
Defined in:
lib/n1_loader/core/preloader.rb

Overview

Preloader that lazily preloads data to every element.

It supports multiple keys.

It supports elements that have different loaders under the same key. It will properly preload data to each of the element of the similar group.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(elements) ⇒ Preloader

Returns a new instance of Preloader.



13
14
15
# File 'lib/n1_loader/core/preloader.rb', line 13

def initialize(elements)
  @elements = elements
end

Instance Attribute Details

#elementsObject (readonly)

Returns the value of attribute elements.



11
12
13
# File 'lib/n1_loader/core/preloader.rb', line 11

def elements
  @elements
end

Instance Method Details

#preload(*keys) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/n1_loader/core/preloader.rb', line 17

def preload(*keys)
  keys.flatten(1).flat_map do |key|
    elements
      .group_by { |element| loader_class(element, key) }
      .select { |loader_class, _| loader_class }
      .map do |(loader_class, grouped_elements)|
        loader_collection = N1Loader::LoaderCollection.new(loader_class, grouped_elements)
        grouped_elements.each { |grouped_element| grouped_element.n1_loaders[key] = loader_collection }
        loader_collection
      end
  end
end