Module: AIXM::Memoize

Overview

Memoize the return value of a specific method across multiple instances for the duration of a block.

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:

class Either
  include AIXM::Memoize

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

a, b, c = Either.new, Either.new, Either.new

# No memoization before the block
$entropy = nil
a.either(1)                 # => 1
b.either(keyword: 2)        # => 2
c.either { 3 }              # => 3
$entropy = :not_nil
a.either(1)                 # => :not_nil
b.either(keyword: 2)        # => :not_nil
c.either { 3 }              # => :not_nil

# Memoization inside the block
AIXM::Memoize.method :either do
  $entropy = nil
  a.either(1)                 # => 1
  b.either(keyword: 2)        # => 2
  c.either { 3 }              # => 3
  $entropy = :not_nil
  a.either(1)                 # => 1          (memoized)
  b.either(keyword: 2)        # => 2          (memoized)
  c.either { 3 }              # => :not_nil   (cannot be memoized)
end

# No memoization after the block
$entropy = nil
a.either(1)                 # => 1
$entropy = :not_nil
a.either(1)                 # => :not_nil

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.cacheObject


84
85
86
# File 'lib/aixm/memoize.rb', line 84

def cache
  (@cache[@method] ||= {}) if @method
end

.included(base) ⇒ Object


71
72
73
74
# File 'lib/aixm/memoize.rb', line 71

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

.method(method) ⇒ Object


76
77
78
79
80
81
82
# File 'lib/aixm/memoize.rb', line 76

def method(method)
  @method = method
  @cache[@method] = {}
  yield
ensure
  @method = nil
end