Class: CacheCrispies::Memoizer

Inherits:
Object
  • Object
show all
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

Constructor Details

#initializeMemoizer

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

Parameters:

  • key (Object)

    the value to use as a cache key

Yields:

  • the value to cache and return if there is a cache miss

Returns:

  • (Object)

    either the cached value or the block’s 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