Skip to content

Instantly share code, notes, and snippets.

@moro
Created May 17, 2013 01:34
Show Gist options
  • Save moro/5596366 to your computer and use it in GitHub Desktop.
Save moro/5596366 to your computer and use it in GitHub Desktop.
retriable
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