Module: AIXM::Concerns::Memoize

Included in:
AIXM::Component::FATO::Direction, AIXM::Component::Runway::Direction, XMLBuilder
Defined in:
lib/aixm/concerns/memoize.rb

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.

Nested memoization of the same method is allowed and won’t reset the memoization cache.

Examples:

class Either
  include AIXM::Concerns::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::Concerns::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 Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.cacheObject (readonly)

Returns the value of attribute cache.



77
78
79
# File 'lib/aixm/concerns/memoize.rb', line 77

def cache
  @cache
end

Class Method Details

.included(base) ⇒ Object



79
80
81
82
# File 'lib/aixm/concerns/memoize.rb', line 79

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

.method(method, &block) ⇒ Object

TODO: [ruby-3.1] use anonymous block “&” on this and next line



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

def method(method, &block)   # TODO: [ruby-3.1] use anonymous block "&" on this and next line
  send(:"call_with#{:out if cached?(method)}_cache", method, &block)
end