Skip to content

Instantly share code, notes, and snippets.

@raul
Created October 7, 2011 06:42
Show Gist options
  • Save raul/1269623 to your computer and use it in GitHub Desktop.
Save raul/1269623 to your computer and use it in GitHub Desktop.
retry_upto.rb
def retry_upto(max_retries = 1, exception_class = Exception)
begin
return yield if ((max_retries -= 1) > 0)
rescue exception_class => e
retry
end
yield
end
@raul
Copy link
Author

raul commented Oct 7, 2011

It's taking a way better shape thanks to @ped and @glenngillen!!!

@raul
Copy link
Author

raul commented Oct 7, 2011

Added :patience feature as I've seen this use case several times too, thanks @jaimeiniesta!

@raul
Copy link
Author

raul commented Oct 7, 2011

Code compacted by @lleirborras, thanks man!

@ltello
Copy link

ltello commented Oct 8, 2011

I usually like to implement Object#first_you_respond_to(*methods) in my apps

Using it my implementation of retry_upto would be:

def retry_upto(max_retries = 1, opts = {})
yield
rescue (opts[:rescue_only] || Exception)
raise if (max_retries -= 1) == 0
if opts[:wait]
meth = opts[:patience].first_you_respond_to(:*, :call)
opts[:wait] = opts[:patience].send(meth, opts[:wait]) if meth
sleep opts[:wait]
end
retry
end

Hope you like it!

@raul
Copy link
Author

raul commented Oct 10, 2011

Sounds nice, though I'd prefer to keep this without external dependencies. I've finally published it as a gem: http://github.com/raul/retry_upto

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment