Class: HttpMagic::Request
- Inherits:
-
Object
- Object
- HttpMagic::Request
- Defined in:
- lib/http_magic/request.rb
Overview
Encapsulating class to hold all of the infrastructure to make the actual requests to the api. It receives at a minimum a HttpMagic::Uri object which manages the url building.
Example
uri_object = HttpMagic::Uri.new('http://example.com')
request = Request.new(uri_object)
request.get
=> { 'name' => 'Foo Bar' }
Instance Method Summary collapse
- #delete ⇒ Object
-
#get ⇒ Object
Makes a GET request to the url provided by the Uri object and returns the resulting JSON data as a Ruby hash.
-
#initialize(uri, options = {}) ⇒ Request
constructor
A new instance of Request.
-
#post ⇒ Object
Makes a POST request to the url provided by the Uri object and returns the resulting JSON data as a Ruby hash.
- #put ⇒ Object
Constructor Details
#initialize(uri, options = {}) ⇒ Request
Returns a new instance of Request.
18 19 20 21 22 23 24 |
# File 'lib/http_magic/request.rb', line 18 def initialize(uri, = {}) @uri = uri @data = [:data] @options = { headers: [:headers] || {} } end |
Instance Method Details
#delete ⇒ Object
26 27 28 |
# File 'lib/http_magic/request.rb', line 26 def delete parse_response http.delete(@uri.urn, @options[:headers]) end |
#get ⇒ Object
Makes a GET request to the url provided by the Uri object and returns the resulting JSON data as a Ruby hash.
Example
uri_object = HttpMagic::Uri.new('http://example.com')
request = Request.new(uri_object)
request.get
=> { 'name' => 'Foo Bar' }
41 42 43 |
# File 'lib/http_magic/request.rb', line 41 def get parse_response http.request_get(@uri.urn, @options[:headers]) end |
#post ⇒ Object
Makes a POST request to the url provided by the Uri object and returns the resulting JSON data as a Ruby hash. If data was provided as an optional initialization parameter, then that is also POSTed.
Example
uri_object = HttpMagic::Uri.new('http://example.com')
request = Request.new(uri_object, data: { name: 'New Foo' })
request.post
56 57 58 59 60 61 62 |
# File 'lib/http_magic/request.rb', line 56 def post if !@data.empty? @options[:headers].merge!( 'Content-Type' => 'application/json' ) end parse_response http.request_post(@uri.urn, @data.to_json, @options[:headers]) end |
#put ⇒ Object
64 65 66 67 68 69 70 |
# File 'lib/http_magic/request.rb', line 64 def put if !@data.empty? @options[:headers].merge!( 'Content-Type' => 'application/json' ) end parse_response http.request_put(@uri.urn, @data.to_json, @options[:headers]) end |