Module: Rodbot::Memoize

Overview

Memoize the return value of a specific method

The method signature is taken into account, therefore calls of the same method with different positional and/or keyword arguments are cached independently. On the other hand, when calling the method with a block, no memoization is performed at all.

Examples:

Explicit declaration

class Either
  include Rodbot::Memoize

  def either(argument=nil, keyword: nil, &block)
    $entropy || argument || keyword || (block.call if block)
  end
  memoize :either
end

Prefixed declaration

class Either
  include Rodbot::Memoize

  memoize def either(argument=nil, keyword: nil, &block)
    $entropy || argument || keyword || (block.call if block)
  end
end

Behaviour of either of the above

e = Either.new
$entropy = nil
e.either(1)                 # => 1
e.either(keyword: 2)        # => 2
e.either { 3 }              # => 3
$entropy = :not_nil
e.either(1)                 # => 1          (memoized)
e.either(keyword: 2)        # => 2          (memoized)
e.either { 3 }              # => :not_nil   (cannot be memoized)
Rodbot::Memoize.suspend do
  e.either(1)               # => 1          (recalculated, not memoized)
end
Rodbot::Memoize.revisit do
  e.either(5)               # => 5          (recalculated, memoized anew)
end

Defined Under Namespace

Modules: ClassMethods

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.cacheObject (readonly)

Returns the value of attribute cache.



70
71
72
# File 'lib/rodbot/memoize.rb', line 70

def cache
  @cache
end

Class Method Details

.included(base) ⇒ Object



72
73
74
75
# File 'lib/rodbot/memoize.rb', line 72

def included(base)
  base.extend(ClassMethods)
  @cache ||= {}
end