Class: Keiyaku::NetHTTPAdapter

Inherits:
Object
  • Object
show all
Includes:
_Adapter
Defined in:
lib/keiyaku/adapters/net_http.rb,
sig/keiyaku.rbs

Overview

Autoloaded from keiyaku/adapters/net_http by the client that was given no adapter, so nothing has to require it to get the default.

Instance Method Summary collapse

Constructor Details

#initialize(timeout: 15) ⇒ NetHTTPAdapter

Returns a new instance of NetHTTPAdapter.

Parameters:

  • timeout: (timeout) (defaults to: 15)


17
18
19
# File 'lib/keiyaku/adapters/net_http.rb', line 17

def initialize(timeout: 15)
  @open_timeout, @read_timeout = Keiyaku.timeouts(timeout)
end

Instance Method Details

#call(verb, uri, headers, body) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/keiyaku/adapters/net_http.rb', line 21

def call(verb, uri, headers, body)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.open_timeout = @open_timeout
  http.read_timeout = @read_timeout

  request = Net::HTTP.const_get(verb.to_s.capitalize).new(uri)
  headers.each { |k, v| request[k] = v }

  if body
    request.body = body
  elsif request.request_body_permitted?
    # No body is no body: an optional one left out means no bytes and no
    # Content-Type claiming there are some, which is the runtime's promise
    # and not this file's to give away. Net::HTTP hands a POST that was
    # given none an empty body of its own, and net/http before 0.5 labels
    # that application/x-www-form-urlencoded — a media type this client
    # never chose, on a request that carries nothing. Saying so here is
    # one method rather than a header to unpick later, and the length
    # still goes out as the zero it is, since a POST without one is what
    # some servers answer with 411.
    request.content_length = 0
    def request.request_body_permitted? = false
  end

  response = http.request(request)
  [response.code.to_i, response.to_hash.transform_values(&:first), response.body]
rescue *TRANSPORT_ERRORS => e
  raise ConnectionError, "#{verb.to_s.upcase} #{uri}: #{e.message}"
end