Class: Zonesync::HTTP

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#baseObject

Returns the value of attribute base

Returns:

  • (Object)

    the current value of base



5
6
7
# File 'lib/zonesync/http.rb', line 5

def base
  @base
end

Instance Method Details

#after_response(&block) ⇒ Object



26
27
28
# File 'lib/zonesync/http.rb', line 26

def after_response &block
  @after_response = block
end

#before_request(&block) ⇒ Object



22
23
24
# File 'lib/zonesync/http.rb', line 22

def before_request &block
  @before_request = block
end

#delete(path) ⇒ Object



18
19
20
# File 'lib/zonesync/http.rb', line 18

def delete path
  request("delete", path)
end

#get(path) ⇒ Object



6
7
8
# File 'lib/zonesync/http.rb', line 6

def get path
  request("get", path)
end

#patch(path, body) ⇒ Object



14
15
16
# File 'lib/zonesync/http.rb', line 14

def patch path, body
  request("patch", path, body)
end

#post(path, body) ⇒ Object



10
11
12
# File 'lib/zonesync/http.rb', line 10

def post path, body
  request("post", path, body)
end

#request(method, path, body = nil) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/zonesync/http.rb', line 30

def request method, path, body=nil
  uri = URI.parse("#{base}#{path}")
  request = Net::HTTP.const_get(method.to_s.capitalize).new(uri.path)

  @before_request.call(request) if @before_request

  response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
    body = JSON.dump(body) if request["Content-Type"].include?("application/json")
    http.request(request, body)
  end

  @after_response.call(response) if @after_response

  raise response.body unless response.code =~ /^20.$/
  if response["Content-Type"].include?("application/json")
    JSON.parse(response.body)
  else
    response.body
  end
end