Sha256: bef939b794c0780f288ff8f4feb46a807593340ef5f830f706880872f9ee6644

Contents?: true

Size: 1.83 KB

Versions: 6

Compression:

Stored size: 1.83 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 #{full_url(path)}")
    rescue Faraday::ConnectionFailed
      begin
        reconnect
        block.call
      rescue Faraday::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

6 entries across 6 versions & 1 rubygems

Version Path
active_rest_client-1.0.2 lib/active_rest_client/connection.rb
active_rest_client-1.0.1 lib/active_rest_client/connection.rb
active_rest_client-1.0.0 lib/active_rest_client/connection.rb
active_rest_client-0.9.75 lib/active_rest_client/connection.rb
active_rest_client-0.9.73 lib/active_rest_client/connection.rb
active_rest_client-0.9.72 lib/active_rest_client/connection.rb