-
-
Save glenngillen/1269733 to your computer and use it in GitHub Desktop.
retry_upto.rb
This file contains 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
# Ruby `retry` with steroids: | |
# | |
# - retry up to 5 times without waiting between them and retrying after any exception | |
# | |
# retry_upto(5) do ... end | |
# | |
# - retry up to 5 times, waiting 2 seconds between retries and retrying after any exception | |
# | |
# retry_upto(5, :wait => 2) do ... end | |
# | |
# - retry up to 5 times without waiting between retries, retrying only after a ZeroDivisionError | |
# | |
# retry_upto(5, :rescue_only => ZeroDivisionError) do ... end | |
# | |
# - retry up to 5 times, waiting 2 seconds between retries, retrying only after a ZeroDivisionError | |
# | |
# retry_upto(5, :wait => 2, :rescue_only => ZeroDivisionError) do ... end | |
def retry_upto(max_retries = 1, options = {}) | |
yield | |
rescue (options[:rescue_only] || Exception) | |
raise if (max_retries -= 1) == 0 | |
sleep(options[:wait] || 0) | |
retry | |
end | |
# Extends enumerator to allow usage like: | |
# | |
# 5.times.retry do | |
# ... | |
# end | |
# | |
class Enumerator | |
def retry(options = {}, &blk) | |
retry_upto(self.count, options, &blk) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment