Skip to content

Instantly share code, notes, and snippets.

@brandonhilkert
Created August 11, 2011 20:12
Show Gist options
  • Save brandonhilkert/1140621 to your computer and use it in GitHub Desktop.
Save brandonhilkert/1140621 to your computer and use it in GitHub Desktop.
module Retryable
def self.included(base)
base.extend(self)
end
# Options:
# * :tries - Number of tries to perform in total, not number of retries. Defaults to 2.
# * :on - The Exception on which a retry will be performed. Defaults to Exception, which retries on any Exception.
# * :hoptoad - a hash of options that will be sent to Hoptoad along w/ the exception on errors
# * :final - Return when the code fails the max number of times
# Example
# =======
# retryable(:tries => 2, :on => OpenURI::HTTPError, :final => "broken...") do
# # your code here
# end
def retryable(options = {}, &block)
opts = {:tries => 2, :on => Exception, :hoptoad => {}, :final => {}}.merge(options)
retry_exception, retries, hoptoad, final = opts[:on], opts[:tries], opts[:hoptoad], opts[:final]
begin
return yield
rescue retry_exception
HoptoadNotifier.notify($!, hoptoad)
retry if (retries -= 1) > 0
end
final
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment