Class: AbstractBuilder::LazyCache
- Inherits:
-
Object
- Object
- AbstractBuilder::LazyCache
- Defined in:
- lib/abstract_builder/lazy_cache.rb
Instance Method Summary collapse
- #add(key, options, &block) ⇒ Object
-
#initialize(driver) ⇒ LazyCache
constructor
A new instance of LazyCache.
- #resolve ⇒ Object
Constructor Details
#initialize(driver) ⇒ LazyCache
Returns a new instance of LazyCache.
3 4 5 6 |
# File 'lib/abstract_builder/lazy_cache.rb', line 3 def initialize(driver) @cache = Hash.new { |h, k| h[k] = {} } @driver = driver end |
Instance Method Details
#add(key, options, &block) ⇒ Object
8 9 10 |
# File 'lib/abstract_builder/lazy_cache.rb', line 8 def add(key, , &block) cache[][key] = block end |
#resolve ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/abstract_builder/lazy_cache.rb', line 12 def resolve resolved = [] # Fail-fast if there is no items to be computed. return resolved if cache.empty? # We can't add new items during interation, so iterate through a clone # that will allow us to add new items. previous = cache.clone cache.clear # Keys are grouped by options and because of that, fetch_multi will use # the same options for the same group of keys. previous.each do |, group| result = driver.fetch_multi(*group.keys, ) do |group_key| [group[group_key].call, *resolve] end # Since the fetch_multi returns { cache_key => value }, we need to # discard the cache key and merge only the values. resolved.concat result.values.flatten(1) end resolved end |