Created
November 28, 2011 18:07
-
-
Save eladkehat/1401347 to your computer and use it in GitHub Desktop.
Utility method that retries a block until it receives some expected result, with some other nifty options
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Retry the block several times, with a timeout between retries | |
# Options: | |
# times - maximum number of retries | |
# timeout - timeout betwen retries, in seconds | |
# break_on - will break the rerty loop given that result from the block | |
# if break_on is a lambda, it will call it with the block result and break if it returns true | |
# @return the block's result | |
def retryable(options = {}, &block) | |
opts = {times:3, timeout:60, break_on:false}.merge(options) | |
(1...opts[:times]).each do |i| | |
res = yield i | |
cond = opts[:break_on] | |
return res if (cond.is_a?(Proc) ? cond.call(res) : cond == res) | |
sleep opts[:timeout] | |
end | |
yield opts[:times] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment