Sha256: 84d5c627815e84a787f6d280f12723092cc564b8a1b6efea25973c82bf495c8e

Contents?: true

Size: 1.09 KB

Versions: 15

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

module N1Loader
  # 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.
  class Preloader
    attr_reader :elements

    def initialize(elements)
      @elements = elements
    end

    def preload(*keys)
      keys.flatten(1).flat_map do |key|
        elements
          .group_by { |element| loader_class(element, key) }
          .map do |loader_class, grouped_elements|
            next unless loader_class

            loader_collection = N1Loader::LoaderCollection.new(loader_class, grouped_elements)
            grouped_elements.each { |grouped_element| grouped_element.n1_loader_set(key, loader_collection) }
            loader_collection
          end.compact
      end
    end

    private

    def loader_class(element, key)
      element.class.respond_to?(:n1_loader_defined?) &&
        element.class.n1_loader_defined?(key) &&
        element.class.n1_loader(key)
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
n1_loader-1.7.1 lib/n1_loader/core/preloader.rb
n1_loader-1.7.0 lib/n1_loader/core/preloader.rb
n1_loader-1.6.6 lib/n1_loader/core/preloader.rb
n1_loader-1.6.5 lib/n1_loader/core/preloader.rb
n1_loader-1.6.4 lib/n1_loader/core/preloader.rb
n1_loader-1.6.3 lib/n1_loader/core/preloader.rb
n1_loader-1.6.2 lib/n1_loader/core/preloader.rb
n1_loader-1.6.1 lib/n1_loader/core/preloader.rb
n1_loader-1.6.0 lib/n1_loader/core/preloader.rb
n1_loader-1.5.1 lib/n1_loader/core/preloader.rb
n1_loader-1.5.0 lib/n1_loader/core/preloader.rb
n1_loader-1.4.4 lib/n1_loader/core/preloader.rb
n1_loader-1.4.3 lib/n1_loader/core/preloader.rb
n1_loader-1.4.2 lib/n1_loader/core/preloader.rb
n1_loader-1.4.1 lib/n1_loader/core/preloader.rb