Class: CacheCrispies::Memoizer
- Inherits:
-
Object
- Object
- CacheCrispies::Memoizer
- Defined in:
- lib/cache_crispies/memoizer.rb
Overview
Simple class to handle memoizing values by a key. This really just provides a bit of wrapper around doing this yourself with a hash.
Instance Method Summary collapse
-
#fetch(key) { ... } ⇒ Object
Fetches a cached value for the given key, if it exists.
-
#initialize ⇒ Memoizer
constructor
A new instance of Memoizer.
Constructor Details
#initialize ⇒ Memoizer
Returns a new instance of Memoizer.
7 8 9 |
# File 'lib/cache_crispies/memoizer.rb', line 7 def initialize @cache = {} end |
Instance Method Details
#fetch(key) { ... } ⇒ Object
Fetches a cached value for the given key, if it exists. Otherwise it calls the block and caches that value
17 18 19 20 21 22 |
# File 'lib/cache_crispies/memoizer.rb', line 17 def fetch(key, &_block) # Avoid ||= because we need to memoize falsey values. return cache[key] if cache.key?(key) cache[key] = yield end |