RSS: Articles| Comments| Trackbacks
 

Ruby Retries 2

Posted by haakon, Fri, 16 Jun 2006 16:20:00 GMT

Benjamin Franklin said, “The definition of insanity is doing the same thing over and over and expecting different results. ” Sometimes, though, a retry is exactly what you need. You may need to call something that is not reliable. Maybe it is a network connection that might be down temporarily. How often have you built retry logic around a bit of code that just might fail on occasion? This snippet takes care of that situation nicely.


class Fixnum
  def tries(message)
    current_try_num = 1
    begin
      yield current_try_num
    rescue => e
      if current_try_num >= self
        raise
      else
        puts "Try #{current_try_num} failed (#{message}): #{e}"
        current_try_num = current_try_num.next
        retry
      end
    end
  end
end

10.tries('doing work') do
  raise 'network connection failed' if rand() < 0.7
  puts 'success'
end

output:
>ruby tries.rb
Try 1 failed (doing work): network connection failed
Try 2 failed (doing work): network connection failed
success

Update! 2007-06-01

This is now available as a ruby gem! To install:

sudo gem install retry

http://retry.rubyforge.org