class Memoizable::Memory
Storage for memoized methods
Public Class Methods
new()
click to toggle source
Initialize the memory storage for memoized methods
@param [ThreadSafe::Cache] memory
@return [undefined]
@api private
# File lib/memoizable/memory.rb, line 14 def initialize @memory = ThreadSafe::Cache.new @monitor = Monitor.new freeze end
Public Instance Methods
[](name)
click to toggle source
Get the value from memory
@param [Symbol] name
@return [Object]
@api public
# File lib/memoizable/memory.rb, line 27 def [](name) @memory.fetch(name) do fail NameError, "No method #{name} is memoized" end end
[]=(name, value)
click to toggle source
Store the value in memory
@param [Symbol] name @param [Object] value
@return [undefined]
@api public
# File lib/memoizable/memory.rb, line 41 def []=(name, value) memoized = true @memory.compute_if_absent(name) do memoized = false value end fail ArgumentError, "The method #{name} is already memoized" if memoized end
fetch(name) { || ... }
click to toggle source
Fetch the value from memory, or store it if it does not exist
@param [Symbol] name
@yieldreturn [Object]
the value to memoize
@api public
# File lib/memoizable/memory.rb, line 58 def fetch(name) @memory.fetch(name) do # check for the key @monitor.synchronize do # acquire a lock if the key is not found @memory.fetch(name) do # recheck under lock self[name] = yield # set the value end end end end
key?(name)
click to toggle source
Test if the name has a value in memory
@param [Symbol] name
@return [Boolean]
@api public
# File lib/memoizable/memory.rb, line 75 def key?(name) @memory.key?(name) end
marshal_dump()
click to toggle source
A hook that allows Marshal to dump the object
@return [Hash]
A hash used to populate the internal memory
@api public
# File lib/memoizable/memory.rb, line 85 def marshal_dump @memory.marshal_dump end
marshal_load(hash)
click to toggle source
A hook that allows Marshal to load the object
@param [Hash] hash
A hash used to populate the internal memory
@return [undefined]
@api public
# File lib/memoizable/memory.rb, line 97 def marshal_load(hash) initialize @memory.marshal_load(hash) end