Class: FutureResource
- Inherits:
-
Object
- Object
- FutureResource
- Defined in:
- lib/future-resource.rb,
lib/future-resource/version.rb
Overview
future-resource allows you to wait on a final value being set for a placeholder, which may occur asynchronously.
Defined Under Namespace
Classes: ResourceAlreadySetException
Constant Summary collapse
- VERSION =
"1.0.0"
Instance Method Summary collapse
-
#initialize ⇒ FutureResource
constructor
Create a new FutureResource.
-
#resource(timeout = nil) ⇒ Object
Returns the value of a specific resource, optionally waiting for
timeoutseconds before raising a Timeout::Error exception. -
#resource=(resource) ⇒ Object
Sets the value for the resource, making it available for all waiting and following reads.
-
#set_yet? ⇒ Boolean
Checks if the value of the resource placeholder has been set yet.
Constructor Details
#initialize ⇒ FutureResource
Create a new FutureResource.
26 27 28 29 |
# File 'lib/future-resource.rb', line 26 def initialize @resource_lock = Monitor.new @resource_value_blocker = @resource_lock.new_cond end |
Instance Method Details
#resource(timeout = nil) ⇒ Object
Returns the value of a specific resource, optionally waiting for timeout seconds before raising a Timeout::Error exception. When called on a not set resource without a timeout, raises a deadlock.
50 51 52 53 54 55 56 57 |
# File 'lib/future-resource.rb', line 50 def resource(timeout = nil) Timeout::timeout timeout do @resource_lock.synchronize do @resource_value_blocker.wait unless defined? @resource @resource end end end |
#resource=(resource) ⇒ Object
Sets the value for the resource, making it available for all waiting and following reads. Resourcs values can only be set once.
66 67 68 69 70 71 72 73 |
# File 'lib/future-resource.rb', line 66 def resource=(resource) @resource_lock.synchronize do raise ResourceAlreadySetException if defined? @resource @resource = resource @resource_value_blocker.broadcast @resource_value_blocker = nil # Don't really need it anymore. end end |
#set_yet? ⇒ Boolean
Checks if the value of the resource placeholder has been set yet.
36 37 38 |
# File 'lib/future-resource.rb', line 36 def set_yet? !!@resource_lock.synchronize { defined? @resource } end |