Jason
Jason

Reputation: 12789

A use case for retry function?

I read this snippet, and I am trying to understand how I can use retry, and I am unable to think of a use. How are others using it?

#!/usr/bin/ruby

for i in 1..5
    retry if  i > 2
    puts "Value of local variable is #{i}"
end

Upvotes: 3

Views: 643

Answers (2)

nroose
nroose

Reputation: 1802

I am using it for a module that makes an api call to a 3rd party web api, and so if it fails, I retry 2 more times.

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176412

There are several use cases. Here's one from the Programming Ruby book

@esmtp = true

begin
  # First try an extended login. If it fails because the
  # server doesn't support it, fall back to a normal login

  if @esmtp then
    @command.ehlo(helodom)
  else
    @command.helo(helodom)
  end

rescue ProtocolError
  if @esmtp then
    @esmtp = false
    retry
  else
    raise
  end
end

An other common case is the email delivery. You might want to retry the SMTP delivery for N times adding a sleep between each retry to avoid temporary issues caused by network connectivity.

Upvotes: 8

Related Questions