Skip to content

Instantly share code, notes, and snippets.

@pedro
Forked from glenngillen/retry_upto.rb
Created October 7, 2011 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedro/1269798 to your computer and use it in GitHub Desktop.
Save pedro/1269798 to your computer and use it in GitHub Desktop.
retry_upto.rb
# Ruby's `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 = {}, &blk)
yield
rescue (options[:rescue_only] || Exception)
sleep(options[:wait] || 0)
retry_upto(max_retries - 1, options, &blk) if max_retries > 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment