class MasterLoader

Constants

VERSION

@!visibility private

Attributes

cache[RW]

Public Class Methods

new(**options, &block) click to toggle source
# File lib/master_loader.rb, line 117
def initialize(**options, &block)
  unless block_given?
    raise TypeError, "Dataloader must be constructed with a block which accepts " \
      "Array and returns either Array or Hash of the same size (or Promise)"
  end

  @name = options.delete(:name)
  @cache = if options.has_key?(:cache)
             options.delete(:cache) || NoCache.new
           else
             Concurrent::Map.new
           end
  @max_batch_size = options.fetch(:max_batch_size, Float::INFINITY)

  @interceptor = options.delete(:interceptor) || -> (n) {
    -> (ids) {
      n.call(ids)
    }
  }

  @loader_block = @interceptor.call(block)
end

Public Instance Methods

batch() click to toggle source
# File lib/master_loader.rb, line 167
def batch
  if @batch.nil? || @batch.fulfilled?
    @batch = Batch.new(@loader_block, name: @name, max_batch_size: @max_batch_size)
  else
    @batch
  end
end
load(key) click to toggle source
# File lib/master_loader.rb, line 140
def load(key)
  if key.nil?
    raise TypeError, "#load must be called with a key, but got: nil"
  end

  result = retrieve_from_cache(key) do
    batch.queue(key)
  end

  if result.is_a?(DelayedResult)
    result
  else
    DelayedResult.new { result }
  end
end
load_many(keys) click to toggle source
# File lib/master_loader.rb, line 156
def load_many(keys)
  unless keys.is_a?(Array)
    raise TypeError, "#load_many must be called with an Array, but got: #{keys.class.name}"
  end

  delayed_results = keys.map(&method(:load))
  DelayedResult.new do
    delayed_results.map(&:value!)
  end
end
retrieve_from_cache(key) { || ... } click to toggle source
# File lib/master_loader.rb, line 175
def retrieve_from_cache(key)
  @cache.compute_if_absent(key) do
    yield
  end
end