Class: Berbix::NetHTTPClient

Inherits:
HTTPClient show all
Defined in:
lib/berbix.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ NetHTTPClient

Returns a new instance of NetHTTPClient.



18
19
20
21
22
# File 'lib/berbix.rb', line 18

def initialize(opts={})
  # Sets the defaults to align with the Net::HTTP defaults
  @open_timeout = opts[:open_timeout] || 60
  @read_timeout = opts[:read_timeout] || 60
end

Instance Attribute Details

#open_timeoutObject (readonly)

Returns the value of attribute open_timeout.



16
17
18
# File 'lib/berbix.rb', line 16

def open_timeout
  @open_timeout
end

#read_timeoutObject (readonly)

Returns the value of attribute read_timeout.



15
16
17
# File 'lib/berbix.rb', line 15

def read_timeout
  @read_timeout
end

Instance Method Details

#request(method, url, headers, opts = {}) ⇒ Object



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
51
52
53
54
55
56
# File 'lib/berbix.rb', line 24

def request(method, url, headers, opts={})
  uri = URI(url)
  klass = if method == :post
    Net::HTTP::Post
  elsif method == :patch
    Net::HTTP::Patch
  elsif method == :delete
    Net::HTTP::Delete
  else
    Net::HTTP::Get
  end
  req = klass.new(uri.to_s, headers)
  unless opts[:data].nil?
    req.body = opts[:data].to_json
  end
  unless opts[:auth].nil?
    req.basic_auth(opts[:auth][:user], opts[:auth][:pass])
  end
  cli = Net::HTTP.new(uri.host, uri.port).tap do |http|
    http.use_ssl = true
    http.read_timeout = read_timeout
    http.open_timeout = open_timeout
  end
  res = cli.request(req)
  code = res.code.to_i
  if code < 200 || code >= 300
    raise(Berbix::BerbixError, "unexpected status code returned: #{code}")
  end
  if code == 204
    return
  end
  JSON.parse(res.body)
end