Module: Mrcr::Cache

Defined in:
lib/mrcr/cache.rb,
lib/mrcr/cache/version.rb

Overview

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

Examples:

require 'mrcr/cache'

class Foo
  extend Mrcr::Cache

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

Defined Under Namespace

Modules: Methods

Constant Summary collapse

VERSION =
'0.1.5'.freeze

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.



22
23
24
25
26
# File 'lib/mrcr/cache.rb', line 22

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.



35
36
37
# File 'lib/mrcr/cache.rb', line 35

def cache
  @__cache__
end

#fetch(key, default = nil) ⇒ 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

Fetch a cache by key & default

Parameters:

  • key (Object)

    Hashable object

  • default (Object) (defaults to: nil)

    Default value

Returns:

  • (Object)

    return value or default



61
62
63
# File 'lib/mrcr/cache.rb', line 61

def fetch(key, default = nil)
  cache.fetch(key.hash, default)
end

#fetch_or_store(key) { ... } ⇒ 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:

  • key (Object)

    Hashable object

Yields:

  • An arbitrary block

Returns:

  • (Object)

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



49
50
51
# File 'lib/mrcr/cache.rb', line 49

def fetch_or_store(key, &block)
  cache.fetch_or_store(key.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.



29
30
31
32
# File 'lib/mrcr/cache.rb', line 29

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