DEV Community

Sahil Gadimbayli
Sahil Gadimbayli

Posted on

Ruby's retry method

Salud to Dev.to community and eager Ruby lovers! It has been a busy month @Camaloon and I will be writing several posts from challenges and solutions in the following weeks.

Today's topic would be Ruby's retry method which I was not familiar until now which came in handy recently.

retry is used when we want to re-execute a code block. This is useful especially when we are trying to send an HTTP request to third-party API and would like several retries in case there are any failures.

As I was not aware of this feature before, when I wanted to re-execute a code block, I would've gone with loops.

Let's look at an example with loops:

We are sending an HTTP request and would like to have 3 retries if it fails due to connection errors.

require 'http'

def send_request(params)
  with_connection_retry { HTTP.post("http://example.com/resource", params: 
    params) }
end

def with_connection_retry
  retries = 0

  loop do
    yield
  rescue HTTP::ConnectionError => e
    retries += 1

    raise e if retries >= 3
  end
end 
Enter fullscreen mode Exit fullscreen mode

This code looked ugly with loop. Let's have a look with retry.

def send_request(params)
  with_connection_retry { HTTP.post("http://example.com/resource", params: 
    params) }
end

def with_connection_retry
  retries ||= 0

  begin
    yield
  rescue HTTP::ConnectionError => e
    retries += 1
    raise e if retries >= 3
    retry
  end
end
Enter fullscreen mode Exit fullscreen mode

So, here you are, using Ruby's native API instead of relying upon loops for re-executing code blocks.

Top comments (0)