Class: Memoizable::Memory

Inherits:
Object
  • Object
show all
Defined in:
lib/memoizable/memory.rb

Overview

Storage for memoized methods

Instance Method Summary collapse

Constructor Details

#initializeundefined

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

Parameters:

  • memory (ThreadSafe::Cache)


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

Parameters:

  • name (Symbol)

Returns:

  • (Object)


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

Parameters:

  • name (Symbol)
  • value (Object)

Returns:

  • (undefined)


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

Parameters:

  • name (Symbol)

Yield Returns:

  • (Object)

    the value to memoize



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

Parameters:

  • name (Symbol)

Returns:

  • (Boolean)


76
77
78
# File 'lib/memoizable/memory.rb', line 76

def key?(name)
  @memory.key?(name)
end

#marshal_dumpHash

A hook that allows Marshal to dump the object

Returns:

  • (Hash)

    A hash used to populate the internal memory



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

Parameters:

  • hash (Hash)

    A hash used to populate the internal memory

Returns:

  • (undefined)


98
99
100
101
# File 'lib/memoizable/memory.rb', line 98

def marshal_load(hash)
  initialize
  @memory.marshal_load(hash)
end