Class: Wimp
- Inherits:
-
Object
- Object
- Wimp
- Defined in:
- lib/wimp.rb
Defined Under Namespace
Instance Attribute Summary collapse
-
#cache ⇒ Object
Returns the value of attribute cache.
Instance Method Summary collapse
- #batch ⇒ Object
-
#initialize(**options, &block) ⇒ Wimp
constructor
A new instance of Wimp.
- #load(key) ⇒ Object
- #load_many(keys) ⇒ Object
- #retrieve_from_cache(key) ⇒ Object
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(**, &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) @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) } } @loader_block = @interceptor.call(block) end |
Instance Attribute Details
#cache ⇒ Object
Returns the value of attribute cache.
115 116 117 |
# File 'lib/wimp.rb', line 115 def cache @cache end |
Instance Method Details
#batch ⇒ Object
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 |