module AIXM::Memoize

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.

@example

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

Public Class Methods

cache() click to toggle source
   # File lib/aixm/memoize.rb
84 def cache
85   (@cache[@method] ||= {}) if @method
86 end
included(base) click to toggle source
   # File lib/aixm/memoize.rb
71 def included(base)
72   base.extend(ClassMethods)
73   @cache = {}
74 end
method(method) { || ... } click to toggle source
   # File lib/aixm/memoize.rb
76 def method(method)
77   @method = method
78   @cache[@method] = {}
79   yield
80 ensure
81   @method = nil
82 end