Sha256: 5fa8c7f3fc8b6510e76eb2616dea760ba2c78deff7a66940898de41f499993e0

Contents?: true

Size: 1.42 KB

Versions: 3

Compression:

Stored size: 1.42 KB

Contents

# Based on: http://danknox.github.io/2013/01/27/using-rubys-native-nethttp-library/
require 'net/http'

module Druid
  class Connection
    CONTENT_TYPE = 'application/json'.freeze
    VERB_MAP = {
      :get    => ::Net::HTTP::Get,
      :post   => ::Net::HTTP::Post,
      :put    => ::Net::HTTP::Put,
      :delete => ::Net::HTTP::Delete
    }

    attr_reader :http

    def initialize(endpoint)
      uri = URI.parse(endpoint)
      @http = ::Net::HTTP.new(uri.host, uri.port)
    end

    def get(path, params = {})
      request :get, path, params
    end

    def post(path, params = {})
      request :post, path, params
    end

    def put(path, params = {})
      request :put, path, params
    end

    def delete(path, params = {})
      request :delete, path, params
    end

    private

    def encode_path_params(path, params)
      encoded = URI.encode_www_form(params)
      [path, encoded].join("?")
    end

    def request(method, path, params)
      case method
      when :get
        full_path = encode_path_params(path, params)
        request = VERB_MAP[method].new(full_path)
      else
        request = VERB_MAP[method].new(path)
        request.body = params.to_json
      end

      request.content_type = CONTENT_TYPE
      begin
        response = http.request(request)
      rescue Timeout::Error, *Druid::NET_HTTP_EXCEPTIONS => e
        raise ConnectionError, e.message
      end

      response
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jruby-druid-1.0.0.pre.rc4 lib/druid/connection.rb
jruby-druid-1.0.0.pre.rc3 lib/druid/connection.rb
jruby-druid-1.0.0.pre.rc2 lib/druid/connection.rb