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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)