class Universa::LazyValue

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.

Public Class Methods

new(&block) click to toggle source

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

# File lib/universa/lazy.rb, line 11
def initialize(&block)
  @value = nil
  @ready = false
  @initializer = block
  @mutex = Mutex.new
end

Public Instance Methods

clear() click to toggle source

causes value to be recalculated on next call to {get}

# File lib/universa/lazy.rb, line 34
def clear
  @ready = false
end
get(&block) click to toggle source

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

# 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