Class: Posthaste::NetHttpTransport

Inherits:
Object
  • Object
show all
Defined in:
lib/posthaste/http_client.rb

Overview

The seam every test stubs.

A transport takes a fully-built request and returns a Response. It knows nothing about retries, authentication or error typing — all of which live in HttpClient — so a test double is four lines and still exercises the whole policy above it.

Instance Method Summary collapse

Constructor Details

#initialize(open_timeout: 10, read_timeout: 30) ⇒ NetHttpTransport

Returns a new instance of NetHttpTransport.



34
35
36
37
# File 'lib/posthaste/http_client.rb', line 34

def initialize(open_timeout: 10, read_timeout: 30)
  @open_timeout = open_timeout
  @read_timeout = read_timeout
end

Instance Method Details

#call(method, url, headers, body) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/posthaste/http_client.rb', line 39

def call(method, url, headers, body)
  uri = URI.parse(url)
  request = Net::HTTP.const_get(method.to_s.capitalize).new(uri)
  headers.each { |name, value| request[name] = value }
  request.body = body if 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
  # Redirects are NOT followed. A 3xx would send the bearer token to
  # whatever host the Location names, so it arrives at the caller as an
  # unhandled answer instead.
  response = http.request(request)

  Response.new(
    status: response.code.to_i,
    body: response.body.to_s,
    headers: response.each_header.to_h
  )
end

#inspectObject

No key here, but the timeouts are the only state and printing them is useful. Defined anyway so the class never inherits a default #inspect if somebody adds an ivar later.



64
65
66
# File 'lib/posthaste/http_client.rb', line 64

def inspect
  "#<Posthaste::NetHttpTransport open_timeout=#{@open_timeout} read_timeout=#{@read_timeout}>"
end