Created
July 14, 2010 08:28
-
-
Save floere/475177 to your computer and use it in GitHub Desktop.
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
class FooError < StandardError; end | |
module BulletProof | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
# blatantly stolen: http://blog.codefront.net/2008/01/14/retrying-code-blocks-in-ruby-on-exceptions-whatever/ | |
def retryable(options = {}, &block) | |
opts = { :tries => 1, :on => Exception }.merge(options) | |
retry_exception, retries = opts[:on], opts[:tries] | |
begin | |
return yield | |
rescue retry_exception => e | |
puts "#{e.class}: #{e.message}" | |
retry if (retries -= 1) > 0 | |
return | |
end | |
yield | |
end | |
module ClassMethods | |
def bulletproof(*methods) | |
opts = methods.last.is_a?(Hash) ? methods.pop : {} | |
tries = opts[:tries] || 1 | |
methods.each do |method| | |
define_method :"#{method}_with_bulletproof" do |*args| | |
retryable(:tries => tries) do | |
send :"#{method}_without_bulletproof", *args | |
end | |
end | |
class_eval %Q{ | |
alias #{method}_without_bulletproof #{method} | |
alias #{method} #{method}_with_bulletproof | |
} | |
end | |
end | |
end | |
end | |
class A | |
include BulletProof | |
def bar(a,b,c) | |
raise FooError, 'bar' | |
end | |
def baz(a) | |
raise 'baz' | |
end | |
bulletproof :bar, :baz, :tries => 2 | |
end | |
a = A.new | |
a.bar(1,2,3) | |
a.baz(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment