Class: Promise

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

Overview

A delayed-execution promise. Promises are only executed once.

Examples:

x = promise { factorial 20 }
y = promise { fibonacci 10**6 }
a = x + 1     # => factorial 20 + 1 after factorial calculates
result = promise { a += y }
abort ""      # whew, we never needed to calculate y
y = 5
x = promise { y = y + 5 }
x + 5     # => 15
x + 5     # => 15

Instance Method Summary collapse

Constructor Details

#initialize(block) ⇒ Promise

Returns a new promise

Parameters:

  • block (Proc)


21
22
23
24
25
26
27
# File 'lib/promise.rb', line 21

def initialize(block)
  if block.arity > 0
    raise ArgumentError, "Cannot store a promise that requires an argument"
  end
  @block = block
  @mutex = ::Mutex.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



40
41
42
43
# File 'lib/promise.rb', line 40

def method_missing(method, *args, &block)
  force unless @result
  @result.send(method, *args, &block)
end

Instance Method Details

#forceAny

Force the evaluation of this promise immediately

Returns:

  • (Any)


31
32
33
34
35
36
37
38
# File 'lib/promise.rb', line 31

def force
  @mutex.synchronize do 
    unless @result
      @result = @block.call
    end
  end
  @result
end