Class: Unparser::Adamantium::Memory

Inherits:
Object
  • Object
show all
Defined in:
lib/unparser/adamantium.rb

Overview

Storage for memoized methods

Instance Method Summary collapse

Constructor Details

#initialize(values) ⇒ 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



46
47
48
49
50
# File 'lib/unparser/adamantium.rb', line 46

def initialize(values)
  @values  = values
  @monitor = Monitor.new
  freeze
end

Instance Method Details

#fetch(name) ⇒ Object

Fetch the value from memory, or evaluate if it does not exist

Parameters:

  • name (Symbol)

Yield Returns:

  • (Object)

    the value to memoize



60
61
62
63
64
65
66
67
68
# File 'lib/unparser/adamantium.rb', line 60

def fetch(name)
  @values.fetch(name) do      # check for the key
    @monitor.synchronize do   # acquire a lock if the key is not found
      @values.fetch(name) do  # recheck under lock
        @values[name] = yield # set the value
      end
    end
  end
end