Class: Memoizable::Memory
- Inherits:
-
Object
- Object
- Memoizable::Memory
- Defined in:
- lib/memoizable/memory.rb
Overview
Storage for memoized methods
Instance Method Summary collapse
-
#[](name) ⇒ Object
Get the value from memory.
-
#[]=(name, value) ⇒ undefined
Store the value in memory.
-
#fetch(name) ⇒ Object
Fetch the value from memory, or store it if it does not exist.
-
#initialize ⇒ undefined
constructor
private
Initialize the memory storage for memoized methods.
-
#key?(name) ⇒ Boolean
Test if the name has a value in memory.
-
#marshal_dump ⇒ Hash
A hook that allows Marshal to dump the object.
-
#marshal_load(hash) ⇒ undefined
A hook that allows Marshal to load the object.
Constructor Details
#initialize ⇒ undefined
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Initialize the memory storage for memoized methods
15 16 17 18 19 |
# File 'lib/memoizable/memory.rb', line 15 def initialize @memory = ThreadSafe::Cache.new @monitor = Monitor.new freeze end |
Instance Method Details
#[](name) ⇒ Object
Get the value from memory
28 29 30 31 32 |
# File 'lib/memoizable/memory.rb', line 28 def [](name) @memory.fetch(name) do fail NameError, "No method #{name} is memoized" end end |
#[]=(name, value) ⇒ undefined
Store the value in memory
42 43 44 45 46 47 48 49 |
# File 'lib/memoizable/memory.rb', line 42 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) ⇒ Object
Fetch the value from memory, or store it if it does not exist
59 60 61 62 63 64 65 66 67 |
# File 'lib/memoizable/memory.rb', line 59 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) ⇒ Boolean
Test if the name has a value in memory
76 77 78 |
# File 'lib/memoizable/memory.rb', line 76 def key?(name) @memory.key?(name) end |
#marshal_dump ⇒ Hash
A hook that allows Marshal to dump the object
86 87 88 |
# File 'lib/memoizable/memory.rb', line 86 def marshal_dump @memory.marshal_dump end |
#marshal_load(hash) ⇒ undefined
A hook that allows Marshal to load the object
98 99 100 101 |
# File 'lib/memoizable/memory.rb', line 98 def marshal_load(hash) initialize @memory.marshal_load(hash) end |