Class: Http::Client

Inherits:
Object
  • Object
show all
Includes:
Chainable
Defined in:
lib/http/client.rb

Overview

Clients make requests and receive responses

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Chainable

#accept, #connect, #default_callbacks, #default_callbacks=, #default_headers, #default_headers=, #default_options=, #delete, #get, #head, #on, #options, #patch, #post, #put, #trace, #with_headers

Constructor Details

#initialize(default_options = {}) ⇒ Client

Returns a new instance of Client.



10
11
12
# File 'lib/http/client.rb', line 10

def initialize(default_options = {})
  @default_options = Options.new(default_options)
end

Instance Attribute Details

#default_optionsObject (readonly)

Returns the value of attribute default_options.



8
9
10
# File 'lib/http/client.rb', line 8

def default_options
  @default_options
end

Instance Method Details

#format_response(method, response, option) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/http/client.rb', line 49

def format_response(method, response, option)
  case option
  when :auto, NilClass
    method == :head ? response : response.parse_body
  when :object
    response
  when :parsed_body
    response.parse_body
  when :body
    response.body
  else raise ArgumentError, "invalid response type: #{option}"
  end
end

#perform(request) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/http/client.rb', line 33

def perform(request)
  uri = request.uri
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true if uri.is_a? URI::HTTPS
  response = http.request request.to_net_http_request

  Http::Response.new.tap do |res|
    response.each_header do |header, value|
      res[header] = value
    end

    res.status = Integer(response.code)
    res.body   = response.body
  end
end

#request(method, uri, options = {}) ⇒ Object

Make an HTTP request



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/http/client.rb', line 15

def request(method, uri, options = {})
  opts = @default_options.merge(options)
  headers = opts.headers

  if opts.form
    body = URI.encode_www_form(opts.form)
    headers['Content-Type'] ||= 'application/x-www-form-urlencoded'
  end

  request = Request.new method, uri, headers, body

  opts.callbacks[:request].each { |c| c.call(request) }
  response = perform request
  opts.callbacks[:response].each { |c| c.call(response) }

  format_response method, response, opts.response
end