class CacheCrispies::Memoizer

Simple class to handle memoizing values by a key. This really just provides a bit of wrapper around doing this yourself with a hash.

Attributes

cache[R]

Public Class Methods

new() click to toggle source
# File lib/cache_crispies/memoizer.rb, line 7
def initialize
  @cache = {}
end

Public Instance Methods

fetch(key) { || ... } click to toggle source

Fetches a cached value for the given key, if it exists. Otherwise it calls the block and caches that value

@param key [Object] the value to use as a cache key @yield the value to cache and return if there is a cache miss @return [Object] either the cached value or the block's value

# 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