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

Posted . Visible to the public.

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

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.

Ulrich Berkmüller
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Ulrich Berkmüller to makandra dev (2012-02-10 11:19)