Read more

Use the "retry" keyword to process a piece of Ruby code again.

Ulrich Berkmueller
February 10, 2012Software engineer

Imagine you have a piece of code that tries to send a request to a remote server. Now the server is temporarily not available and raises an exception. In order to re-send the request you could use the following snippet:

def remote_request
  begin
    response = RestClient.get my_request_url
  rescue RestClient::ResourceNotFound => error
    @retries ||= 0
    if @retries < @max_retries
      @retries += 1
      retry
    else
      raise error
    end
  end
  response
end
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

This snippet tries to re-send the request when ResourceNotFound was thrown until @max_retries (termination condition) was reached. With the retry statement you can re-execute the begin block that has been rescued from. Be aware that you could run into an infinite loop without a termination condition.

Posted by Ulrich Berkmueller to makandra dev (2012-02-10 12:19)