Class: MasterLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/master_loader.rb,
lib/master_loader/version.rb
more...

Defined Under Namespace

Classes: Batch, Cache, NoCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options, &block) ⇒ MasterLoader

Returns a new instance of MasterLoader.

[View source]

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/master_loader.rb', line 115

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
             Cache.new
           end
  @max_batch_size = options.fetch(:max_batch_size, Float::INFINITY)

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

  @loader_block = @interceptor.call(block)
end

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.


113
114
115
# File 'lib/master_loader.rb', line 113

def cache
  @cache
end

Instance Method Details

#batchObject

[View source]

161
162
163
164
165
166
167
# File 'lib/master_loader.rb', line 161

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) ⇒ Object

Raises:

  • (TypeError)
[View source]

138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/master_loader.rb', line 138

def load(key)
  raise TypeError, "#load must be called with a key, but got: nil" if key.nil?

  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) ⇒ Object

Raises:

  • (TypeError)
[View source]

152
153
154
155
156
157
158
159
# File 'lib/master_loader.rb', line 152

def load_many(keys)
  raise TypeError, "#load_many must be called with an Array, but got: #{keys.class.name}" unless keys.is_a?(Array)

  delayed_results = keys.map(&method(:load))
  DelayedResult.new do
    delayed_results.map(&:value!)
  end
end

#retrieve_from_cache(key, &block) ⇒ Object

[View source]

169
170
171
# File 'lib/master_loader.rb', line 169

def retrieve_from_cache(key, &block)
  @cache.compute_if_absent(key, &block)
end