module Dry::Core::Cache

Allows you to cache call results that are solely determined by arguments.

@example

require 'dry/core/cache'

class Foo
  extend Dry::Core::Cache

  def heavy_computation(arg1, arg2)
    fetch_or_store(arg1, arg2) { arg1 ^ arg2 }
  end
end

@api public

Public Class Methods

extended(klass) click to toggle source

@api private

Calls superclass method
# File lib/dry/core/cache.rb, line 23
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/dry/core/cache.rb, line 36
def cache
  @__cache__
end
fetch_or_store(*args, &block) click to toggle source

Caches a result of the block evaluation

@param [Array<Object>] args List of hashable objects @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/dry/core/cache.rb, line 51
def fetch_or_store(*args, &block)
  cache.fetch_or_store(args.hash, &block)
end
inherited(klass) click to toggle source

@api private

Calls superclass method
# File lib/dry/core/cache.rb, line 30
def inherited(klass)
  super
  klass.instance_variable_set(:@__cache__, cache)
end