Module: HttpHelper

Defined in:
lib/unit/utils/http_helper.rb

Class Method Summary collapse

Class Method Details

.append_key(root_key, key) ⇒ Object



53
54
55
# File 'lib/unit/utils/http_helper.rb', line 53

def self.append_key(root_key, key)
  root_key.nil? ? key : "#{root_key}[#{key}]"
end

.delete(url, body:, headers:) ⇒ Object



24
25
26
# File 'lib/unit/utils/http_helper.rb', line 24

def self.delete(url, body:, headers:)
  make_request(Net::HTTP::Delete, url, headers, body: body)
end

.encode(value, key = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/unit/utils/http_helper.rb', line 43

def self.encode(value, key = nil)
  case value
  when Hash then value.map { |k, v| encode(v, append_key(key, k)) }.join("&")
  when Array then value.map { |v| encode(v, "#{key}[]") }.join("&")
  when nil then ""
  else
    "#{key}=#{CGI.escape(value.to_s)}"
  end
end

.get(url, headers:, params: nil) ⇒ Object



8
9
10
# File 'lib/unit/utils/http_helper.rb', line 8

def self.get(url, headers:, params: nil)
  make_request(Net::HTTP::Get, url, headers, params: params)
end

.make_request(net_http, url, headers, body: nil, params: nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/unit/utils/http_helper.rb', line 28

def self.make_request(net_http, url, headers, body: nil, params: nil)
  uri = params.nil? ? URI(url) : URI("#{url}?#{encode(params)}")
  host = uri.host.to_s
  port = uri.port
  options = { use_ssl: uri.scheme == "https" }

  Net::HTTP.start(host, port, options) do |http|
    request = net_http.new uri, headers
    request.body = body unless body.nil?
    response = http.request request
    response.body = JSON.parse(response.body)
    response
  end
end

.patch(url, body:, headers:) ⇒ Object



20
21
22
# File 'lib/unit/utils/http_helper.rb', line 20

def self.patch(url, body:, headers:)
  make_request(Net::HTTP::Patch, url, headers, body: body)
end

.post(url, headers:, body: nil) ⇒ Object



12
13
14
# File 'lib/unit/utils/http_helper.rb', line 12

def self.post(url, headers:, body: nil)
  make_request(Net::HTTP::Post, url, headers, body: body)
end

.put(url, body:, headers:) ⇒ Object



16
17
18
# File 'lib/unit/utils/http_helper.rb', line 16

def self.put(url, body:, headers:)
  make_request(Net::HTTP::Put, url, headers, body: body)
end