Class: Swagger::Request

Inherits:
Object show all
Defined in:
lib/swagger/request.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_method, path, attributes = {}) ⇒ Request

All requests must have an HTTP method and a path Optionals parameters are :params, :headers, :body, :format, :host



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/swagger/request.rb', line 15

def initialize(http_method, path, attributes={})
  attributes[:format] ||= Swagger.configuration.format
  attributes[:params] ||= {}

  # Set default headers
  default_headers = {
    'Content-Type' => "application/#{attributes[:format].downcase}",
    :api_key => Swagger.configuration.api_key,
    'User-Agent' => Swagger.configuration.user_agent
  }

  # api_key from headers hash trumps the default, even if its value is blank
  if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
    default_headers.delete(:api_key)
  end
  
  # api_key from params hash trumps all others (headers and default_headers)
  if attributes[:params].present? && attributes[:params].has_key?(:api_key)
    default_headers.delete(:api_key)
    attributes[:headers].delete(:api_key) if attributes[:headers].present?
  end
  
  # Merge argument headers into defaults
  attributes[:headers] = default_headers.merge(attributes[:headers] || {})
  
  # Stick in the auth token if there is one
  if Swagger.authenticated?
    attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
  end
        
  self.http_method = http_method.to_sym
  self.path = path
  attributes.each do |name, value|
    send("#{name.to_s.underscore.to_sym}=", value)
  end
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



9
10
11
# File 'lib/swagger/request.rb', line 9

def body
  @body
end

#form_paramsObject

Returns the value of attribute form_params.



9
10
11
# File 'lib/swagger/request.rb', line 9

def form_params
  @form_params
end

#formatObject

Returns the value of attribute format.



9
10
11
# File 'lib/swagger/request.rb', line 9

def format
  @format
end

#headersObject

Returns the value of attribute headers.



9
10
11
# File 'lib/swagger/request.rb', line 9

def headers
  @headers
end

#hostObject

Returns the value of attribute host.



9
10
11
# File 'lib/swagger/request.rb', line 9

def host
  @host
end

#http_methodObject

Returns the value of attribute http_method.



9
10
11
# File 'lib/swagger/request.rb', line 9

def http_method
  @http_method
end

#paramsObject

Returns the value of attribute params.



9
10
11
# File 'lib/swagger/request.rb', line 9

def params
  @params
end

#pathObject

Returns the value of attribute path.



9
10
11
# File 'lib/swagger/request.rb', line 9

def path
  @path
end

Instance Method Details

#interpreted_pathObject

Iterate over the params hash, injecting any path values into the path string

e.g. /word.#format/word/entries => /word.json/cat/entries



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/swagger/request.rb', line 74

def interpreted_path
  p = self.path.dup

  # Stick a .{format} placeholder into the path if there isn't
  # one already or an actual format like json or xml
  # e.g. /words/blah => /words.{format}/blah
  if Swagger.configuration.inject_format
    unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
      p = p.sub(/^(\/?\w+)/, "\\1.#{format}")
    end
  end

  # Stick a .{format} placeholder on the end of the path if there isn't
  # one already or an actual format like json or xml
  # e.g. /words/blah => /words/blah.{format}
  if Swagger.configuration.force_ending_format
    unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
      p = "#{p}.#{format}"   
    end
  end

  p = p.sub("{format}", self.format.to_s)
  
  URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
end

#makeObject



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/swagger/request.rb', line 154

def make
  #TODO use configuration setting to determine if debugging
  #logger = Logger.new STDOUT
  #logger.debug self.url
  response = case self.http_method.to_sym
  when :get,:GET
    Typhoeus::Request.get(
      self.url,
      :headers => self.headers.stringify_keys,
    )

  when :post,:POST
    Typhoeus::Request.post(
      self.url,
      :body => self.outgoing_body,
      :headers => self.headers.stringify_keys,
    )

  when :patch,:PATCH
    Typhoeus::Request.patch(
      self.url,
      :body => self.outgoing_body,
      :headers => self.headers.stringify_keys,
    )

  when :put,:PUT
    Typhoeus::Request.put(
      self.url,
      :body => self.outgoing_body,
      :headers => self.headers.stringify_keys,
    )
  
  when :delete,:DELETE
    Typhoeus::Request.delete(
      self.url,
      :body => self.outgoing_body,
      :headers => self.headers.stringify_keys,
    )
  end
  Response.new(response)
end

#outgoing_bodyObject

If body is an object, JSONify it before making the actual request. For form parameters, remove empty value



115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/swagger/request.rb', line 115

def outgoing_body
  # http form
  if @body.nil? && @form_params && !@form_params.empty?
    data = form_params.dup
    data.each do |key, value|
      data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
    end
    data
  else # http body is JSON
    @body.is_a?(String) ? @body : @body.to_json
  end
end

#query_stringObject

Construct a query string from the query-string-type params



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/swagger/request.rb', line 129

def query_string

  # Iterate over all params,
  # .. removing the ones that are part of the path itself.
  # .. stringifying values so Addressable doesn't blow up.
  query_values = {}
  self.params.each_pair do |key, value|
    next if self.path.include? "{#{key}}"                                   # skip path params
    next if value.blank? && value.class != FalseClass                       # skip empties
    if Swagger.configuration.camelize_params
      key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key    # api_key is not a camelCased param
    end
    query_values[key] = value.to_s
  end

  # We don't want to end up with '?' as our query string
  # if there aren't really any params
  return "" if query_values.blank?

  # Addressable requires query_values to be set after initialization..
  qs = Addressable::URI.new
  qs.query_values = query_values
  qs.to_s
end

#responseObject



196
197
198
# File 'lib/swagger/request.rb', line 196

def response
  self.make
end

#response_code_prettyObject



200
201
202
203
# File 'lib/swagger/request.rb', line 200

def response_code_pretty
  return unless @response.present?
  @response.code.to_s    
end

#response_headers_prettyObject



205
206
207
208
209
# File 'lib/swagger/request.rb', line 205

def response_headers_pretty
  return unless @response.present?
  # JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
  @response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end

#url(options = {}) ⇒ Object

Construct a base URL



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/swagger/request.rb', line 54

def url(options = {})  
  u = Addressable::URI.new(
    :scheme => Swagger.configuration.scheme,
    :host => Swagger.configuration.host,
    :path => self.interpreted_path,
    :query => self.query_string.sub(/\?/, '')
  ).to_s
  
  # Drop trailing question mark, if present
  u.sub! /\?$/, ''
  
  # Obfuscate API key?
  u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated]
  
  u
end