##
# Retry a _block_ of statements upto a number of _times_.
# When no error is raised the value returned by _block_ is
# simply returned.
#
# === Examples
#
# try 3 do
# open 'http://vision-media.ca'
# end
# # => allows 3 tries to fetch the response
#
def try times = 1, options = {}, &block
yield
rescue options[:on] || Exception
retry if (times -= 1) > 0
end
Refactorings
No refactoring yet !
Muke Tever
October 12, 2009, October 12, 2009 12:15, permalink
Well, it looks fine. Though IMO it looks like it ought to be parallel to "3.times do", so:
class Integer
def tries options = {}, &block
return if self < 1
yield attempts ||= 1
rescue options[:ignoring] || Exception
retry if (attempts += 1) <= self
end
end
3.tries { open 'http://vision-media.ca' }
3.tries do |i|
puts "Try ##{i} at opening..."
open 'http://vision-media.ca'
end
3.tries(:ignoring => ParticularException) do
open 'http://vision-media.ca'
end
# etc.
I know &block does not need to be present, but i prefer to have it shown, makes it more obvious that blocks are allowed IMO