Class: Wimp

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

Defined Under Namespace

Classes: Batch, NoCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Wimp.



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/wimp.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

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.



115
116
117
# File 'lib/wimp.rb', line 115

def cache
  @cache
end

Instance Method Details

#batchObject



167
168
169
170
171
172
173
# File 'lib/wimp.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) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/wimp.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) ⇒ Object



156
157
158
159
160
161
162
163
164
165
# File 'lib/wimp.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) ⇒ Object



175
176
177
178
179
# File 'lib/wimp.rb', line 175

def retrieve_from_cache(key)
  @cache.compute_if_absent(key) do
    yield
  end
end