Sha256: 47e779d664877f6d00dfece584429ba118c3c5af88ff3f5216c2b9d50d6bc5cb

Contents?: true

Size: 1.69 KB

Versions: 4

Compression:

Stored size: 1.69 KB

Contents

require 'faraday'

module ActiveRestClient

  class TimeoutException < StandardError ; end
  class ConnectionFailedException < StandardError ; end

  class Connection
    attr_accessor :session, :base_url

    def initialize(base_url)
      @base_url                      = base_url
      @session                       = new_session
    end

    def reconnect
      @session         = new_session
    end

    def headers
      @session.headers
    end

    def make_safe_request(path, &block)
      block.call
    rescue Faraday::TimeoutError
      raise ActiveRestClient::TimeoutException.new("Timed out getting #{@base_url}#{path}")
    rescue Faraday::ConnectionFailed
      begin
        reconnect
        block.call
      rescue Faraday::ConnectionFailed
        raise ActiveRestClient::ConnectionFailedException.new("Unable to connect to #{@base_url}#{path}")
      end
    end

    def get(path, headers={})
      make_safe_request(path) do
        @session.get(path) do |req|
          req.headers = headers
        end
      end
    end

    def put(path, data, headers={})
      make_safe_request(path) do
        @session.put(path) do |req|
          req.headers = headers
          req.body = data
        end
      end
    end

    def post(path, data, headers={})
      make_safe_request(path) do
        @session.post(path) do |req|
          req.headers = headers
          req.body = data
        end
      end
    end

    def delete(path, headers={})
      make_safe_request(path) do
        @session.delete(path) do |req|
          req.headers = headers
        end
      end
    end

    private

    def new_session
      Faraday.new({url: @base_url}, &ActiveRestClient::Base.faraday_config)
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
active_rest_client-0.9.70 lib/active_rest_client/connection.rb
active_rest_client-0.9.69 lib/active_rest_client/connection.rb
active_rest_client-0.9.68 lib/active_rest_client/connection.rb
active_rest_client-0.9.67 lib/active_rest_client/connection.rb