Class: Motion::HTTP::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/common/http/request.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_method, url, options = nil) ⇒ Request

Returns a new instance of Request.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/common/http/request.rb', line 6

def initialize(http_method, url, options = nil)
  @http_method = http_method
  @url = url
  @options = options ||= {}
  @headers = @options.delete(:headers) || Headers.new
  @body = @options.delete(:body)

  if @options[:params]
    @params = @options.delete(:params)
    flatten_params!
    encode_params!
    @url = "#{url}?#{@params.map{|k,v|"#{k}=#{v}"}.join('&')}"

  elsif @options[:form]
    @headers['Content-Type'] ||= 'application/x-www-form-urlencoded'
    @params = @options.delete(:form)
    flatten_params!
    encode_params!
    @body = @params.map{|k,v|"#{k}=#{v}"}.join('&')

  elsif @options[:json]
    @headers['Content-Type'] ||= 'application/json; charset=utf-8'
    @body = @options.delete(:json).to_json
  end
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



4
5
6
# File 'lib/common/http/request.rb', line 4

def body
  @body
end

#headersObject (readonly)

Returns the value of attribute headers.



4
5
6
# File 'lib/common/http/request.rb', line 4

def headers
  @headers
end

#http_methodObject (readonly)

Returns the value of attribute http_method.



4
5
6
# File 'lib/common/http/request.rb', line 4

def http_method
  @http_method
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/common/http/request.rb', line 4

def options
  @options
end

#urlObject (readonly)

Returns the value of attribute url.



4
5
6
# File 'lib/common/http/request.rb', line 4

def url
  @url
end

Instance Method Details

#encode_params!Object



47
48
49
50
51
52
53
# File 'lib/common/http/request.rb', line 47

def encode_params!
  new_params = {}
  @params.each do |k,v|
    new_params[ParamsEncoder.encode(k)] = ParamsEncoder.encode(v)
  end
  @params = new_params
end

#flatten_params!Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/common/http/request.rb', line 32

def flatten_params!
  new_params = {}
  @params.each do |k,v|
    if v.is_a? Hash
      v.each do |nested_k, nested_v|
        new_params["#{k}[#{nested_k}]"] = nested_v
      end
    else
      new_params[k] = v
    end
  end
  @params = new_params
  flatten_params! if @params.any? {|k,v| v.is_a? Hash }
end

#perform(&callback) ⇒ Object



55
56
57
58
# File 'lib/common/http/request.rb', line 55

def perform(&callback)
  Motion::HTTP.logger.log_request(self)
  Adapter.perform(self, &callback)
end