Class: GiantClient::NetHttpAdapter

Inherits:
AbstractAdapter show all
Defined in:
lib/giant_client/net_http_adapter.rb

Instance Method Summary collapse

Methods inherited from AbstractAdapter

#delete, #encode_query, #get, #head, #normalize_header, #normalize_header_hash, #post, #prepend_question_mark, #put, #stringify_query, #url_from_opts

Instance Method Details

#normalize_response(response) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/giant_client/net_http_adapter.rb', line 43

def normalize_response(response)
  status_code = response.code.to_i
  headers = {}
  response.each_header do |header, value|
    header = normalize_header(header)
    headers[header] = value
  end
  body = response.body
  Response.new(status_code, headers, body)
end

#request(method, opts) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/giant_client/net_http_adapter.rb', line 7

def request(method, opts)
  if BODYLESS_METHODS.include?(method)
    raise GiantClient::Error::NotImplemented unless opts[:body] == ''
  end
  query = encode_query(opts[:query])

  http = Net::HTTP.new( opts[:host], opts[:port] )
  http.use_ssl = opts[:ssl]
  http.read_timeout = opts[:timeout]
  http.open_timeout = opts[:timeout]

  request_class =
    case method
      when :get then Net::HTTP::Get
      when :post then Net::HTTP::Post
      when :put then Net::HTTP::Put
      when :delete then Net::HTTP::Delete
      when :head then Net::HTTP::Head
    end

  request = request_class.new( opts[:path] + query, opts[:headers] )

  if request.request_body_permitted?
    request.body = opts[:body]
  end

  begin
    response = http.start {|http| http.request(request)}
  rescue Timeout::Error
    raise GiantClient::Error::Timeout, "the request timed out (timeout: #{opts[:timeout]}"
  end

  # make response object
  normalize_response(response)
end