• How to retry SSH, API, and external connections in Rails 4

This is pretty much a no-brainer, but in case you’re in doubt, this is an easy way to retry external connections. This way you don’t automatically halt the application at the slightest network issues.

I’m using Peakium as an example of API connection, but you can do this with pretty much anything as long as you rescue from the right exception type (should only be in case there is connectivity issue).

# models/concerns/peakium_retry.rb
module PeakiumRetry
  def peakium_retry(&block)
    retries = 1
    begin
      block.call
    rescue Peakium::APIConnectionError => e
      raise e if retries == 0
      retries -= 1
      sleep 0.5
      retry
    end
  end
end

This will retry the connection one time if failing (waiting half a second between tries), and throw the exception if it fails again.

You will just do the call like this:

events = peakium_retry do
  Peakium::Event.all(params, peakium_access_token).data
end

Straight forward, and easy.

The Author

Dan Schultzer is an active experienced entrepreneur, starting the Being Proactive groups, Dream Conception organization, among other things. You can find him at twitter

Like this post? More from Dan Schultzer

Comments? We would love to hear from you, write us at @dreamconception.