Class: Garcon::LazyReference

Inherits:
Object
  • Object
show all
Defined in:
lib/garcon/task/lazy_reference.rb

Overview

Lazy evaluation of a block yielding an immutable result. Useful for expensive operations that may never be needed. ‘LazyReference` is a simpler, blocking version of `Delay` and has an API similar to `AtomicReference`. The first time `#value` is called the caller will block until the block given at construction is executed. Once the result has been computed the value will be immutably set. Any exceptions thrown during computation will be suppressed.

Instance Method Summary collapse

Constructor Details

#initialize(default = nil) { ... } ⇒ LazyReference

Creates a new unfulfilled object.

Parameters:

  • default (Object) (defaults to: nil)

    The default value for the object when the block raises an exception.

Yields:

  • the delayed operation to perform

Raises:

  • (ArgumentError)

    if no block is given



41
42
43
44
45
46
47
48
# File 'lib/garcon/task/lazy_reference.rb', line 41

def initialize(default = nil, &block)
  raise ArgumentError, 'no block given' unless block_given?
  @default   = default
  @task      = block
  @mutex     = Mutex.new
  @value     = nil
  @fulfilled = false
end

Instance Method Details

#valueObject

The calculated value of the object or the default value if one was given at construction. This first time this method is called it will block indefinitely while the block is processed. Subsequent calls will not block.

Returns:

  • (Object)

    the calculated value



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/garcon/task/lazy_reference.rb', line 57

def value
  return @value if @fulfilled

  @mutex.synchronize do
    unless @fulfilled
      begin
        @value = @task.call
      rescue
        @value = @default
      ensure
        @fulfilled = true
      end
    end
    return @value
  end
end