Class: Hellio::NetHttpAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/hellio/http.rb

Overview

Default HTTP adapter built on the standard library net/http. Tests (or advanced users) can inject any object that responds to #call with the same keyword arguments and returns an object exposing #status and #body.

Instance Method Summary collapse

Instance Method Details

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



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/hellio/http.rb', line 14

def call(method:, url:, headers:, body:, timeout:)
  uri = URI.parse(url)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == "https")
  http.open_timeout = timeout
  http.read_timeout = timeout

  request_class =
    case method
    when :get then Net::HTTP::Get
    when :post then Net::HTTP::Post
    when :delete then Net::HTTP::Delete
    else raise ArgumentError, "Unsupported HTTP method: #{method}"
    end

  request = request_class.new(uri.request_uri)
  headers.each { |key, value| request[key] = value }
  request.body = body unless body.nil?

  response = http.request(request)
  Response.new(response.code.to_i, response.body.to_s)
end