Class: Promise
- Inherits:
-
Object
- Object
- Promise
- Defined in:
- lib/promise.rb
Overview
A delayed-execution promise. Promises are only executed once.
Constant Summary collapse
- NOT_SET =
::Object.new.freeze
Instance Method Summary collapse
-
#__force__ ⇒ Any
(also: #force)
Force the evaluation of this promise immediately.
-
#initialize(block) ⇒ Promise
constructor
Create a new promise.
- #method_missing(method, *args, &block) ⇒ Object
-
#respond_to?(method) ⇒ true, false
Does this promise support the given method?.
Constructor Details
#initialize(block) ⇒ Promise
Create a new promise
28 29 30 31 32 33 34 35 36 |
# File 'lib/promise.rb', line 28 def initialize(block) if block.arity > 0 raise ArgumentError, "Cannot store a promise that requires an argument" end @block = block @mutex = ::Mutex.new @result = NOT_SET @error = NOT_SET end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
66 67 68 69 |
# File 'lib/promise.rb', line 66 def method_missing(method, *args, &block) __force__ @result.send(method, *args, &block) end |
Instance Method Details
#__force__ ⇒ Any Also known as: force
Force the evaluation of this promise immediately
42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/promise.rb', line 42 def __force__ @mutex.synchronize do if @result == NOT_SET && @error == NOT_SET begin @result = @block.call rescue ::Exception => e @error = e end end end if @result == NOT_SET && @error == NOT_SET # BasicObject won't send raise to Kernel @error.equal?(NOT_SET) ? @result : (::Kernel.raise @error) end |
#respond_to?(method) ⇒ true, false
Does this promise support the given method?
62 63 64 |
# File 'lib/promise.rb', line 62 def respond_to?(method) (method == :force) || (method == :__force__) || (__force__.respond_to?(method)) end |