Skip to content

Instantly share code, notes, and snippets.

@hannestyden
Created February 25, 2010 17:53
Show Gist options
  • Save hannestyden/314815 to your computer and use it in GitHub Desktop.
Save hannestyden/314815 to your computer and use it in GitHub Desktop.
# Inspired by/stolen from: http://refactormycode.com/codes/1065-retry
require 'logger'
module Kernel
def logger
@logger = Logger.new(STDOUT)
end
end
class MyRuntimeError < RuntimeError; end
class YourRuntimeError < RuntimeError; end
class Integer
def attempts(options={}, &block)
return if self < 1
yield attempt_counter ||= 1
rescue *options[:ignoring] || Exception
logger.error("** Error while making attempt #{attempt_counter} of #{self}: #{$!.inspect}") if options[:log]
retry if (attempt_counter += 1) <= self
end
end
first = 3.attempts(:ignoring => [ MyRuntimeError ], :log => true) do |attempt|
if attempt < 3
raise MyRuntimeError, "This is my error and will be ignored."
else
:ok
end
end
first # => :ok
second = 3.attempts(:ignoring => [ MyRuntimeError ], :log => true) do |attempt|
raise MyRuntimeError, "This is my error and will be ignored."
end || :not_ok
second # => :not_ok
third = 3.attempts(:ignoring => [ MyRuntimeError ], :log => true) do |attempt|
if attempt < 3
raise YourRuntimeError, "This is your error and will not be ignored."
end
end
third # =>
# ~> -:38:in `block in <main>': This is your error and will not be ignored. (YourRuntimeError)
# ~> from -:15:in `attempts'
# ~> from -:36:in `<main>'
# >> E, [2010-02-25T18:51:04.924612 #52779] ERROR -- : ** Error while making attempt 1 of 3: #<MyRuntimeError: This is my error and will be ignored.>
# >> E, [2010-02-25T18:51:04.925050 #52779] ERROR -- : ** Error while making attempt 2 of 3: #<MyRuntimeError: This is my error and will be ignored.>
# >> E, [2010-02-25T18:51:04.925246 #52779] ERROR -- : ** Error while making attempt 1 of 3: #<MyRuntimeError: This is my error and will be ignored.>
# >> E, [2010-02-25T18:51:04.925287 #52779] ERROR -- : ** Error while making attempt 2 of 3: #<MyRuntimeError: This is my error and will be ignored.>
# >> E, [2010-02-25T18:51:04.925324 #52779] ERROR -- : ** Error while making attempt 3 of 3: #<MyRuntimeError: This is my error and will be ignored.>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment