Class: Zonesync::HTTP
- Inherits:
-
Struct
- Object
- Struct
- Zonesync::HTTP
- Extended by:
- T::Sig
- Defined in:
- lib/zonesync/http.rb
Instance Attribute Summary collapse
-
#base ⇒ Object
Returns the value of attribute base.
Instance Method Summary collapse
- #after_response(&block) ⇒ Object
- #before_request(&block) ⇒ Object
- #delete(path) ⇒ Object
- #get(path) ⇒ Object
-
#initialize(base) ⇒ HTTP
constructor
A new instance of HTTP.
- #patch(path, body) ⇒ Object
- #post(path, body) ⇒ Object
- #request(method, path, body = nil) ⇒ Object
Constructor Details
#initialize(base) ⇒ HTTP
Returns a new instance of HTTP.
12 13 14 15 16 |
# File 'lib/zonesync/http.rb', line 12 def initialize(base) super @before_request = T.let([], T::Array[T.untyped]) @after_response = T.let([], T::Array[T.untyped]) end |
Instance Attribute Details
#base ⇒ Object
Returns the value of attribute base
8 9 10 |
# File 'lib/zonesync/http.rb', line 8 def base @base end |
Instance Method Details
#after_response(&block) ⇒ Object
44 45 46 |
# File 'lib/zonesync/http.rb', line 44 def after_response &block @after_response << block end |
#before_request(&block) ⇒ Object
39 40 41 |
# File 'lib/zonesync/http.rb', line 39 def before_request &block @before_request << block end |
#delete(path) ⇒ Object
34 35 36 |
# File 'lib/zonesync/http.rb', line 34 def delete path request("delete", path) end |
#get(path) ⇒ Object
19 20 21 |
# File 'lib/zonesync/http.rb', line 19 def get path request("get", path) end |
#patch(path, body) ⇒ Object
29 30 31 |
# File 'lib/zonesync/http.rb', line 29 def patch path, body request("patch", path, body) end |
#post(path, body) ⇒ Object
24 25 26 |
# File 'lib/zonesync/http.rb', line 24 def post path, body request("post", path, body) end |
#request(method, path, body = nil) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/zonesync/http.rb', line 49 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.each do |block| block.call(request, uri, body) end response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| if request.fetch("Content-Type", "").include?("application/json") http.request(request, JSON.dump(body)) else http.request(request, body) end end @after_response.each do |block| block.call(response) end raise response.body unless response.code =~ /^20.$/ if response["Content-Type"].include?("application/json") JSON.parse(response.body) else response.body end end |