Class: HttpMagic::Request

Inherits:
Object
  • Object
show all
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

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, options = {})
  @uri = uri
  @data = options[:data]
  @options = {
    headers: options[:headers] || {}
  }
end

Instance Method Details

#deleteObject



26
27
28
# File 'lib/http_magic/request.rb', line 26

def delete
  parse_response http.delete(@uri.urn, @options[:headers])
end

#getObject

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

#postObject

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

#putObject



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