module Mrcr::Cache
Allows you to cache call results that are solely determined by arguments.
@example
require 'mrcr/cache' class Foo extend Mrcr::Cache def heavy_computation(arg1, arg2) fetch_or_store(arg1) { arg1 ^ arg2 } fetch(arg1, nil) end end
@api public
Constants
- VERSION
Public Class Methods
extended(klass)
click to toggle source
@api private
Calls superclass method
# File lib/mrcr/cache.rb, line 22 def self.extended(klass) super klass.include(Methods) klass.instance_variable_set(:@__cache__, Concurrent::Map.new) end
Public Instance Methods
cache()
click to toggle source
@api private
# File lib/mrcr/cache.rb, line 35 def cache @__cache__ end
fetch(key, default = nil)
click to toggle source
Fetch a cache by key & default
@param [Object] key Hashable object @param [Object] default Default value
@note (see fetch_or_store
)
@return [Object] return value or default
# File lib/mrcr/cache.rb, line 61 def fetch(key, default = nil) cache.fetch(key.hash, default) end
fetch_or_store(key, &block)
click to toggle source
Caches a result of the block evaluation
@param [Object] key Hashable object @yield An arbitrary block
@note beware Proc instance hashes are not equal, i.e. -> { 1 }.hash != -> { 1 }.hash,
this means you shouldn't pass Procs in args unless you're sure they are always the same instances, otherwise you introduce a memory leak
@return [Object] block's return value (cached for subsequent calls with the same argument values)
# File lib/mrcr/cache.rb, line 49 def fetch_or_store(key, &block) cache.fetch_or_store(key.hash, &block) end
inherited(klass)
click to toggle source
@api private
Calls superclass method
# File lib/mrcr/cache.rb, line 29 def inherited(klass) super klass.instance_variable_set(:@__cache__, cache) end