Tips – How to write ruby retry

Posted by AllenWei | Posted in RubyOnRails, Tips | Posted on 15-02-2010-05-2008

View Comments




<br
  retry_times = 3
  begin
    # Exception here
  rescue Exception => e
    retry if (retry_times -= 1 ) > 0
  end

Retryable method I wrote:

  # If you want to get a proxy but afraid of proxy failture, you can use this method.
  # If retry times more than retry times in option parameter, will raise a RetryError.
  # * :retry_times - Retry times , Defaults 10
  # * :on - The Exception on which a retry will be performed. Defaults Exception
  # Notice: This method will call block many times, so don't put can't retryable code in it.
  # Example
  # =======
  #    begin
  #      retryable_proxy(:retry_times => 10,:on => Timeout::Error) do |ip,port|
  #         # your code here
  #      end
  #    rescue RetryError
  #      # handle error
  #    end
  #
  def retryable_proxy(options = {},&block)
    opts = {:retry_times => 10,:on => Exception}.merge(options)
    retry_times, try_exception = opts[:retry_times], opts[:on]
    begin
      proxy = Lookup::Models::ProxyList.random
      return block.call(proxy.ip,proxy.port)
    rescue try_exception => e
      retry if (retry_times -= 1) > 0
    end
    raise RetryError
  end


Ads Plugin created by Jake Ruston's Wordpress Plugins - Powered by and football database.