Retryable is another handy gem that lets you repeat a code block after an exception has happened. It has a really easy syntax, and comes with many customizations, that make it a great tool to use, especially when you have to work with web services.

You can install it by simply adding the following in your Gemfile:

gem ‘retryable’

You can use many parameters to configure it based on your needs, such the number of iterations:

require "open-uri"

Retryable.retryable(:tries => 2) do
  xml = open("URL").read

type of exceptions:

require "open-uri"

Retryable.retryable(:on => OpenURI::HTTPError) do
  xml = open("URL").read

the pattern that should be matched:

Retryable.retryable(:matching => /Invalid parameter/) do |retries, exception|
  raise "Invalid parameter submitted" if retries == 0

You can also make the code block take a break using :sleep and the number of seconds that you want the break to last before the new execution of code block begins.

It can even be used to specify the type of call back that you want to execute when the exception is thrown:

span style="font-weight: 400;">exception_cb = do |exception|
  ExceptionNotifier.notify_exception(exception, :data => {:message => "An exception has been thrown"})

Retryable.retryable(:exception_cb => exception_cb) do


You can also disable it in certain occasions when you need to do so:

span style="font-weight: 400;">Retryable.enabled?
=> true


=> false

There are other methods to repeat a code block in Ruby when a particular exception is thrown, for example begin, rescue, retry cycle. Retryable is just another cool one that joins the party, and makes it even more beautiful to code in Ruby. As it comes with so many parameters that can easily be specified, it makes it really worth giving it a try.

The power of choice is part of the autonomy, which ultimately contributes to motivation. Having the opportunity to choose between so many alternatives for the same thing is really inspiring.

You can learn more about this gem and also view its source code by going to this Github repository.