Class: ShortCircuIt::MemoizationStore

Inherits:
Object
  • Object
show all
Defined in:
lib/short_circu_it/memoization_store.rb

Instance Method Summary collapse

Constructor Details

#initialize(owner) ⇒ MemoizationStore

Returns a new instance of MemoizationStore.

Parameters:

  • owner (*)

    The object being memoized



10
11
12
# File 'lib/short_circu_it/memoization_store.rb', line 10

def initialize(owner)
  @owner = owner
end

Instance Method Details

#clear_all_memoizationObject

Clears all memoized values on the object



37
38
39
# File 'lib/short_circu_it/memoization_store.rb', line 37

def clear_all_memoization
  memoized_hash.clear
end

#clear_memoization(method_name) ⇒ Boolean

Clears all cached values for the given method

Parameters:

  • method_name (Symbol)

    The name of a memoized method

Returns:

  • (Boolean)

    True if a value was cleared, false if not



32
33
34
# File 'lib/short_circu_it/memoization_store.rb', line 32

def clear_memoization(method_name)
  !!memoized_hash.delete(method_name)
end

#inspectObject



41
42
43
# File 'lib/short_circu_it/memoization_store.rb', line 41

def inspect
  "#<#{self.class} memoized: #{memoized_hash.keys.inspect}>"
end

#memoize(method_name, argument_hash) { ... } ⇒ *

Returns The value returned either from the memoization cache if present, or yielded block if not.

Parameters:

  • method_name (Symbol)

    The name of the method being memoized.

  • argument_hash (Integer)

    The hash value of the arguments passed to the method.

Yields:

  • Yields to a given block with no arguments. Memoizes the value returned by the block.

Returns:

  • (*)

    The value returned either from the memoization cache if present, or yielded block if not.



18
19
20
21
22
23
24
25
26
# File 'lib/short_circu_it/memoization_store.rb', line 18

def memoize(method_name, argument_hash)
  return memoized_value(method_name, argument_hash) if memoized?(method_name, argument_hash)

  clear_memoization(method_name) unless current_memoization_for_method?(method_name)

  yield.tap do |returned_value|
    current_memoization_for_method(method_name)[argument_hash] = returned_value
  end
end