Skip to content

Instantly share code, notes, and snippets.

@colinsurprenant
Created December 14, 2010 21:43
Show Gist options
  • Save colinsurprenant/741159 to your computer and use it in GitHub Desktop.
Save colinsurprenant/741159 to your computer and use it in GitHub Desktop.
Retryable Ruby module
module Praized
module Slingshot
module Retryable
# execute retryable code block
# thanks to http://blog.codefront.net/2008/01/14/retrying-code-blocks-in-ruby-on-exceptions-whatever/ fo original idea
# @param [Hash] options retryable options
# @option options [Fixnum] :tries retries to perform, default 1.
# @option options [Exception] :on exception on which a retry will be performed, defaults is Exception, which retries on any Exception.
# @option options [Proc] :before_retry call the given Proc/lambda with the raised exception as parameter
#
# @author Colin Surprenant
# @since 1.0
def retryable(options = {}, &block)
_options = {:tries => 1, :on => Exception, :before_retry => lambda{|e|}}.merge(options)
clazz, retries, before_retry = _options[:on], _options[:tries], _options[:before_retry]
begin
return yield
rescue clazz => e
before_retry.call(e)
retry if (retries -= 1) > 0
end
yield
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment