Class: Thread::Delay
- Inherits:
-
Object
- Object
- Thread::Delay
- Defined in:
- lib/thread/delay.rb
Overview
A delay is an object that incapsulates a block which is called upon value retrieval, and its result cached.
Instance Method Summary collapse
-
#delivered? ⇒ Boolean
(also: #realized?)
Check if the delay has been called.
-
#exception ⇒ Object
Return the raised exception.
-
#exception? ⇒ Boolean
Check if an exception has been raised.
-
#initialize(&block) ⇒ Delay
constructor
Create a delay with the passed block.
-
#value ⇒ Object
(also: #~)
Get the value of the delay, if it’s already been executed, return the cached result, otherwise execute the block and return the value.
-
#value! ⇒ Object
(also: #!)
Do the same as #value, but return nil in case of exception.
Constructor Details
#initialize(&block) ⇒ Delay
Create a delay with the passed block.
17 18 19 20 21 22 |
# File 'lib/thread/delay.rb', line 17 def initialize (&block) raise ArgumentError, 'no block given' unless block @mutex = Mutex.new @block = block end |
Instance Method Details
#delivered? ⇒ Boolean Also known as: realized?
Check if the delay has been called.
39 40 41 42 43 |
# File 'lib/thread/delay.rb', line 39 def delivered? @mutex.synchronize { instance_variable_defined? :@value } end |
#exception ⇒ Object
Return the raised exception.
32 33 34 35 36 |
# File 'lib/thread/delay.rb', line 32 def exception @mutex.synchronize { @exception } end |
#exception? ⇒ Boolean
Check if an exception has been raised.
25 26 27 28 29 |
# File 'lib/thread/delay.rb', line 25 def exception? @mutex.synchronize { instance_variable_defined? :@exception } end |
#value ⇒ Object Also known as: ~
Get the value of the delay, if it’s already been executed, return the cached result, otherwise execute the block and return the value.
In case the block raises an exception, it will be raised, the exception is cached and will be raised every time you access the value.
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/thread/delay.rb', line 52 def value @mutex.synchronize { raise @exception if instance_variable_defined? :@exception return @value if instance_variable_defined? :@value begin @value = @block.call rescue Exception => e @exception = e raise end } end |
#value! ⇒ Object Also known as: !
Do the same as #value, but return nil in case of exception.
71 72 73 74 75 76 77 |
# File 'lib/thread/delay.rb', line 71 def value! begin value rescue Exception nil end end |