Notes on building cloud software and systems for humans

Endless HTTParty Retries in Ruby With a Simple Block

See also: A Ruby HOWTO: Writing A Method That Uses Code Blocks

# Simple wrapper to allow retries for HTTP requests - prolongs daemon life.
def with_http_retries(&block)
  begin
    yield
  rescue Errno::ECONNREFUSED, SocketError, Net::ReadTimeout
    DaemonKit.logger.error "Cannot reach [#{@service_url}]. Retrying in #{@retry_seconds} seconds."
    sleep @retry_seconds
    retry
  end
end

# DRYing up the connection params
@request_params = [@service_url,
      { headers: { "Authorization" => "Token token=#{api_key}" }, timeout: 5 }]

loop do
  response = with_http_retries { HTTParty.get *@request_params }

  puts JSON.parse(response.body)

  sleep @delay_seconds
end