I am not certain whether the ability to retry a code block when encountering exceptions was a feature available in Ruby, but I certainly couldn’t find anything on that topic (what I did find were mostly about the retry keyword for iterator loops).
Before you ask why I need this, the motivation for this was because I was getting intermittent HTTP errors (503s mostly) trying to connect to a web service. Turns out it’s really easy in Ruby to implement a retryable method that does something like this:
retryable(:tries => 5, :on => OpenURI::HTTPError) do
open('http://example.com/flaky_api')
# Code that mashes up stuff for your "social networking" site.
end
Here are the Kernel#retryable specs (pastie).
And the code:
# Options:
# * :tries - Number of retries to perform. Defaults to 1.
# * :on - The Exception on which a retry will be performed. Defaults to Exception, which retries on any Exception.
#
# Example
# =======
# retryable(:tries => 1, :on => OpenURI::HTTPError) do
# # your code here
# end
#
def retryable(options = {}, &block)
opts = { :tries => 1, :on => Exception }.merge(options)
retry_exception, retries = opts[:on], opts[:tries]
begin
return yield
rescue retry_exception
retry if (retries -= 1) > 0
end
yield
end
It’s not hard to implement the same for checking return values as well, i.e.
retryable_deluxe(:tries => 5, :on => { :return => nil }) { puts "working..." }
retryable_deluxe(:on => { :exception => StandardError, :return => nil }) do
# your code here
end
Ruby is nice.