Created
May 17, 2013 01:34
-
-
Save moro/5596366 to your computer and use it in GitHub Desktop.
retriable
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 Retriable | |
class RepeatedError < RuntimeError | |
def initialize(max, *args) | |
@errors = [] | |
@max = max | |
super(*args) | |
end | |
def <<(e) | |
@errors << e | |
end | |
def still_retriable? | |
@max > error_count | |
end | |
def error_count | |
@errors.size | |
end | |
end | |
def with_retry(max_retry = 3) | |
repeatable_error = Retriable::RepeatedError.new(max_retry) | |
begin | |
return yield | |
rescue => ex | |
repeatable_error << ex | |
if repeatable_error.still_retriable? | |
sleep 3 * 2 ** (repeatable_error.error_count - 1) | |
retry | |
else | |
raise repeatable_error | |
end | |
end | |
end | |
end | |
class Foo | |
include Retriable | |
def hi(max) | |
n = 0 | |
with_retry do | |
p :hi | |
n += 1 | |
raise if n < max | |
end | |
end | |
end | |
Foo.new.hi(3) | |
Foo.new.hi(4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment