Created
December 14, 2010 21:43
-
-
Save colinsurprenant/741159 to your computer and use it in GitHub Desktop.
Retryable Ruby module
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
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