Sha256: 8877994bb90200d9423cd453c3ad26d10ff2163da50aa6f559ff4a1ec7ce7da6

Contents?: true

Size: 1.85 KB

Versions: 5

Compression:

Stored size: 1.85 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::Error::TimeoutError
      raise ActiveRestClient::TimeoutException.new("Timed out getting #{full_url(path)}")
    rescue Faraday::Error::ConnectionFailed
      begin
        reconnect
        block.call
      rescue Faraday::Error::ConnectionFailed
        raise ActiveRestClient::ConnectionFailedException.new("Unable to connect to #{full_url(path)}")
      end
    end

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

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

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

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

    private

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


    def full_url(path)
      @session.build_url(path).to_s
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
active_rest_client-1.0.7 lib/active_rest_client/connection.rb
active_rest_client-1.0.6 lib/active_rest_client/connection.rb
active_rest_client-1.0.5 lib/active_rest_client/connection.rb
active_rest_client-1.0.4 lib/active_rest_client/connection.rb
active_rest_client-1.0.3 lib/active_rest_client/connection.rb