Module: Waiter
- Defined in:
- lib/vapir-common/waiter.rb
Class Method Summary collapse
-
.try_for(time, options = {}) ⇒ Object
Tries for
time
seconds to get the desired result from the given block.
Class Method Details
.try_for(time, options = {}) ⇒ Object
Tries for time
seconds to get the desired result from the given block. Stops when either:
-
The :condition option (which should be a proc) returns true (that is, not false or nil)
-
The block returns true (that is, anything but false or nil) if no :condition option is given
-
The specified amount of time has passed. By default a WaiterError is raised. If :exception option is given, then if it is nil, no exception is raised; otherwise it should be an exception class or an exception instance which will be raised instead of WaiterError
Returns the value of the block, which can be handy for things that return nil on failure and some other object on success, like Enumerable#detect for example:
found_thing=Waiter.try_for(30){ all_things().detect{|thing| thing.name=="Bill" } }
Examples:
Waiter.try_for(30) do
Time.now.year == 2015
end
Raises a WaiterError unless it is called between the last 30 seconds of December 31, 2014 and the end of 2015
Waiter.try_for(365*24*60*60, :interval => 0.1, :exception => nil, :condition => proc{ 2+2==5 }) do
STDERR.puts "any decisecond now ..."
end
Complains to STDERR for one year, every tenth of a second, as long as 2+2 does not equal 5. Does not raise an exception if 2+2 does not become equal to 5.
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/vapir-common/waiter.rb', line 74 def self.try_for(time, ={}) unless time.is_a?(Numeric) && .is_a?(Hash) raise TypeError, "expected arguments are time (a numeric) and, optionally, options (a Hash). received arguments #{time.inspect} (#{time.class}), #{.inspect} (#{.class})" end =(, {:interval => 0.5, :condition => proc{|_ret| _ret}, :exception => WaiterError}) started=Time.now begin ret=yield break if [:condition].call(ret) sleep [:interval] end while Time.now < started+time && ![:condition].call(ret) if [:exception] && ![:condition].call(ret) ex=if [:exception].is_a?(Class) [:exception].new("Waiter waited #{time} seconds and condition was not met") else [:exception] end raise ex end ret end |