From: "Ara.T.Howard" Date: 2005-07-30T00:24:15+09:00 Subject: Re: Allow retry to take arguments? On Fri, 29 Jul 2005, Austin Ziegler wrote: > It's a neat idea, though, and I think that it could be generally > useful, not just database useful. i use these in my personal lib (http://codeforpeople.com/lib/ruby/alib/): # # initiates a catch block to do 'something'. if the method try_again! is # called the block is done over - if the method give_up! is called the block # is aborted. calls to attempt may be nested. # def attempt label = 'attempt' ret = nil n_attempts = 0 loop{ break unless catch("#{ label }"){ ret = yield(n_attempts += 1) } == 'try_again' } ret end # # see attempt # def try_again! label = 'attempt' throw "#{ label }", 'try_again' end # # see attempt # def give_up! label = 'attempt' throw "#{ label }", 'give_up' end usage like attempt do |n_attempts| begin db = connect rescue sleep 2 and try_again! if n_attempts < 3 end end and can be nested like attempt('connect') do |connect_attempts| begin db = connect attempt('transaction') do |transaction_attempts| begin db.execute sql rescue => e case e when ConnectionError sleep 2 and try_again!('connect') if connection_attempts < 3 when TransactionError sleep 3 and try_again!('transaction') if transaction_attempts < 4 else raise end end end rescue sleep 2 and try_again!('connect') if connection_attempts < 3 end end and end up using it alot for network type code. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | My religion is very simple. My religion is kindness. | --Tenzin Gyatso ===============================================================================