The wait gem executes a block until there's a valid (by default, truthy) result. Useful for blocking script execution until:
- an HTTP request was successful
- a port has opened
- a process has started
- etc.
Add to your Gemfile:
gem "wait", "~> 0.5.1"wait = Wait.new
# => #<Wait>
wait.until { Time.now.sec.even? }
# [Counter] attempt 1/5
# [Tester] result: false
# [Rescuer] rescued: Wait::ResultInvalid
# [Raiser] not raising: Wait::ResultInvalid
# [Delayer] delaying for 1s
# [Counter] attempt 2/5
# [Tester] result: true
# => trueIf you wish to handle an exception by attempting the block again, pass one or an array of exceptions with the :rescue option.
wait = Wait.new(:rescue => RuntimeError)
# => #<Wait>
wait.until do |attempt|
case attempt
when 1 then nil
when 2 then raise RuntimeError
when 3 then "foo"
end
end
# [Counter] attempt 1/5
# [Tester] result: nil
# [Rescuer] rescued: Wait::ResultInvalid
# [Raiser] not raising: Wait::ResultInvalid
# [Delayer] delaying for 1s
# [Counter] attempt 2/5
# [Rescuer] rescued: RuntimeError
# [Raiser] not raising: RuntimeError
# [Delayer] delaying for 1s
# [Counter] attempt 3/5
# [Tester] result: "foo"
# => "foo"- attempts
- Number of times to attempt the block. Default is
5. - timeout
- Seconds until the block times out. Default is
15. - delay
- Seconds to delay in between attempts. Default is
1. - rescue
- One or an array of exceptions to rescue. Default is
nil. - debug
- If
true, debug logging is enabled. Default isfalse.
- logger
- Ruby logger used. Default is
Wait::BaseLogger. - counter
- Strategy used to count attempts. Default is
Wait::BaseCounter. - delayer
- Strategy used to delay in between attempts. Default is
Wait::RegularDelayer. - rescuer
- Strategy used to rescue exceptions. Default is
Wait::BaseRescuer. - tester
- Strategy used to test the result. Default is
Wait::TruthyTester. - raiser
- Strategy used to raise specific exceptions. Default is
Wait::SignalRaiser.
RDoc-generated documentation available here.