Class: Universa::LazyValue

Inherits:
Object
  • Object
show all
Defined in:
lib/universa/lazy.rb

Overview

Experimental!

Memoizable lazy pattern. A value that is calculated only once and onlywhen first time #get is called. LazyValue is thread-safe and calculates its value exactly once.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ LazyValue

initialize lazy value with an optional initializer block. If no initializer block is given, then #get call must provide one.



11
12
13
14
15
16
# File 'lib/universa/lazy.rb', line 11

def initialize(&block)
  @value = nil
  @ready = false
  @initializer = block
  @mutex = Mutex.new
end

Instance Method Details

#clearObject

causes value to be recalculated on next call to #get



34
35
36
# File 'lib/universa/lazy.rb', line 34

def clear
  @ready = false
end

#get(&block) ⇒ Object

Get the value, calculating it using initializer block specified in the params or at creation time if no block is provided



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/universa/lazy.rb', line 20

def get(&block)
  @mutex.synchronize {
    if @ready
      @value
    else
      @initializer = block if block
      @value = @initializer.call
      @ready = true
      @value
    end
  }
end