Sha256: 5aedcb1d76b0b7bd109370e4cf3f9a38253a4800517f3c07b6d29d4ecdbbbb48

Contents?: true

Size: 1.98 KB

Versions: 5

Compression:

Stored size: 1.98 KB

Contents

require 'patron'

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                       = Patron::Session.new
      @session.timeout               = 10
      @session.connect_timeout       = 10
      @session.base_url              = base_url
      @session.insecure              = true
      @session.headers['User-Agent'] = "ActiveRestClient/#{ActiveRestClient::VERSION}"
      @session.headers['Connection'] = "Keep-Alive"
      @session.headers['Accept']     = "application/json"
    end

    def reconnect
      session          = Patron::Session.new
      session.timeout  = @session.timeout
      session.base_url = @session.base_url
      session.insecure              = true
      @session.headers.each do |k,v|
        session.headers[k] = v
      end
      @session         = session
    end

    def headers
      @session.headers
    end

    def make_safe_request(path, &block)
      block.call
    rescue Patron::TimeoutError
      raise ActiveRestClient::TimeoutException.new("Timed out getting #{@base_url}#{path}")
    rescue Patron::ConnectionFailed
      begin
        reconnect
        block.call
      rescue Patron::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, headers)
      end
    end

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

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

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

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
active_rest_client-0.9.66 lib/active_rest_client/connection.rb
active_rest_client-0.9.65 lib/active_rest_client/connection.rb
active_rest_client-0.9.60 lib/active_rest_client/connection.rb
active_rest_client-0.9.59 lib/active_rest_client/connection.rb
active_rest_client-0.9.58 lib/active_rest_client/connection.rb