Class: Strongman
- Inherits:
-
Object
- Object
- Strongman
- Defined in:
- lib/strongman.rb,
lib/strongman/version.rb
Defined Under Namespace
Instance Attribute Summary collapse
-
#cache ⇒ Object
Returns the value of attribute cache.
Instance Method Summary collapse
- #batch ⇒ Object
- #depends_on(**options, &block) ⇒ Object
-
#initialize(**options, &block) ⇒ Strongman
constructor
A new instance of Strongman.
- #load(key) ⇒ Object
- #load_many(keys) ⇒ Object
- #retrieve_from_cache(key) ⇒ Object
Constructor Details
#initialize(**options, &block) ⇒ Strongman
Returns a new instance of Strongman.
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'lib/strongman.rb', line 200 def initialize(**, &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 = .delete(:name) @parent = .delete(:parent) @cache = if .has_key?(:cache) .delete(:cache) || NoCache.new else Concurrent::Map.new end @max_batch_size = .fetch(:max_batch_size, Float::INFINITY) @interceptor = .delete(:interceptor) || -> (n) { -> (ids) { n.call(ids) } } if @parent @interceptor = @interceptor.call(-> (n) { -> (ids) { n.call(@parent, ids) } }) end @loader_block = @interceptor.call(block) end |
Instance Attribute Details
#cache ⇒ Object
Returns the value of attribute cache.
198 199 200 |
# File 'lib/strongman.rb', line 198 def cache @cache end |
Instance Method Details
#batch ⇒ Object
261 262 263 264 265 266 267 |
# File 'lib/strongman.rb', line 261 def batch if @batch.nil? || @batch.fulfilled? @batch = Batch.new(@loader_block, name: @name, parent: @parent&.batch, max_batch_size: @max_batch_size) else @batch end end |
#depends_on(**options, &block) ⇒ Object
232 233 234 |
# File 'lib/strongman.rb', line 232 def depends_on(**, &block) Strongman.new(**, parent: self, &block) end |
#load(key) ⇒ Object
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
# File 'lib/strongman.rb', line 236 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?(Concurrent::Promises::Future) result else Concurrent::Promises.future {result} end end |
#load_many(keys) ⇒ Object
252 253 254 255 256 257 258 259 |
# File 'lib/strongman.rb', line 252 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 promises = keys.map(&method(:load)) Concurrent::Promises.zip_futures(*promises).then {|*results| results} end |
#retrieve_from_cache(key) ⇒ Object
269 270 271 272 273 |
# File 'lib/strongman.rb', line 269 def retrieve_from_cache(key) @cache.compute_if_absent(key) do yield end end |