Module: Dry::Core::Cache

Defined in:
lib/dry/core/cache.rb

Overview

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

Examples:

require 'dry/core/cache'

class Foo
  extend Dry::Core::Cache

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

Defined Under Namespace

Modules: Methods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



21
22
23
24
25
# File 'lib/dry/core/cache.rb', line 21

def self.extended(klass)
  super
  klass.include(Methods)
  klass.instance_variable_set(:@__cache__, Concurrent::Map.new)
end

Instance Method Details

#cacheObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



34
35
36
# File 'lib/dry/core/cache.rb', line 34

def cache
  @__cache__
end

#fetch_or_store(*args) { ... } ⇒ Object

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

Caches a result of the block evaluation

Parameters:

  • args (Array<Object>)

    List of hashable objects

Yields:

  • An arbitrary block

Returns:

  • (Object)

    block’s return value (cached for subsequent calls with the same argument values)



48
49
50
# File 'lib/dry/core/cache.rb', line 48

def fetch_or_store(*args, &block)
  cache.fetch_or_store(args.hash, &block)
end

#inherited(klass) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



28
29
30
31
# File 'lib/dry/core/cache.rb', line 28

def inherited(klass)
  super
  klass.instance_variable_set(:@__cache__, cache)
end