1 # Copyright 2010 Google Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
16 require 'addressable/uri'
17 require 'addressable/template'
19 require 'google/api_client/errors'
25 # A method that has been described by a discovery document.
29 # Creates a description of a particular method.
31 # @param [Addressable::URI] method_base
32 # The base URI for the service.
33 # @param [String] method_name
34 # The identifier for the method.
35 # @param [Hash] method_description
36 # The section of the discovery document that applies to this method.
38 # @return [Google::APIClient::Method] The constructed method object.
39 def initialize(api, method_base, method_name, discovery_document)
41 @method_base = method_base
43 @discovery_document = discovery_document
47 # Returns the identifier for the method.
49 # @return [String] The method identifier.
53 # Returns the parsed section of the discovery document that applies to
56 # @return [Hash] The method description.
57 attr_reader :description
60 # Returns the base URI for the method.
62 # @return [Addressable::URI]
63 # The base URI that this method will be joined to.
64 attr_reader :method_base
67 # Updates the method with the new base.
69 # @param [Addressable::URI, #to_str, String] new_base
70 # The new base URI to use for the method.
71 def method_base=(new_method_base)
72 @method_base = Addressable::URI.parse(new_method_base)
77 # Returns the method ID.
79 # @return [String] The method identifier.
81 return @discovery_document['id']
85 # Returns the HTTP method or 'GET' if none is specified.
87 # @return [String] The HTTP method that will be used in the request.
89 return @discovery_document['httpMethod'] || 'GET'
93 # Returns the URI template for the method. A parameter list can be
94 # used to expand this into a URI.
96 # @return [Addressable::Template] The URI template.
98 # TODO(bobaman) We shouldn't be calling #to_s here, this should be
99 # a join operation on a URI, but we have to treat these as Strings
100 # because of the way the discovery document provides the URIs.
101 # This should be fixed soon.
102 return @uri_template ||= Addressable::Template.new(
103 self.method_base + @discovery_document['path']
108 # Returns the Schema object for the method's request, if any.
110 # @return [Google::APIClient::Schema] The request schema.
112 if @discovery_document['request']
113 schema_name = @discovery_document['request']['$ref']
114 return @api.schemas[schema_name]
121 # Returns the Schema object for the method's response, if any.
123 # @return [Google::APIClient::Schema] The response schema.
125 if @discovery_document['response']
126 schema_name = @discovery_document['response']['$ref']
127 return @api.schemas[schema_name]
134 # Normalizes parameters, converting to the appropriate types.
136 # @param [Hash, Array] parameters
137 # The parameters to normalize.
139 # @return [Hash] The normalized parameters.
140 def normalize_parameters(parameters={})
141 # Convert keys to Strings when appropriate
142 if parameters.kind_of?(Hash) || parameters.kind_of?(Array)
143 # Returning an array since parameters can be repeated (ie, Adsense Management API)
144 parameters = parameters.inject([]) do |accu, (k, v)|
145 k = k.to_s if k.kind_of?(Symbol)
146 k = k.to_str if k.respond_to?(:to_str)
147 unless k.kind_of?(String)
148 raise TypeError, "Expected String, got #{k.class}."
155 "Expected Hash or Array, got #{parameters.class}."
161 # Expands the method's URI template using a parameter list.
163 # @param [Hash, Array] parameters
164 # The parameter list to use.
166 # @return [Addressable::URI] The URI after expansion.
167 def generate_uri(parameters={})
168 parameters = self.normalize_parameters(parameters)
169 self.validate_parameters(parameters)
170 template_variables = self.uri_template.variables
171 uri = self.uri_template.expand(parameters)
172 query_parameters = parameters.reject do |k, v|
173 template_variables.include?(k)
175 if query_parameters.size > 0
176 uri.query_values = (uri.query_values || []) + query_parameters
178 # Normalization is necessary because of undesirable percent-escaping
179 # during URI template expansion
184 # Generates an HTTP request for this method.
186 # @param [Hash, Array] parameters
187 # The parameters to send.
188 # @param [String, StringIO] body The body for the HTTP request.
189 # @param [Hash, Array] headers The HTTP headers for the request.
191 # @return [Array] The generated HTTP request.
192 def generate_request(parameters={}, body='', headers=[])
193 if body.respond_to?(:string)
195 elsif body.respond_to?(:to_str)
198 raise TypeError, "Expected String or StringIO, got #{body.class}."
200 if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
201 raise TypeError, "Expected Hash or Array, got #{headers.class}."
203 method = self.http_method
204 uri = self.generate_uri(parameters)
205 headers = headers.to_a if headers.kind_of?(Hash)
206 return [method, uri.to_str, headers, [body]]
210 # Returns a <code>Hash</code> of the parameter descriptions for
213 # @return [Hash] The parameter descriptions.
214 def parameter_descriptions
215 @parameter_descriptions ||= (
216 @discovery_document['parameters'] || {}
217 ).inject({}) { |h,(k,v)| h[k]=v; h }
221 # Returns an <code>Array</code> of the parameters for this method.
223 # @return [Array] The parameters.
226 @discovery_document['parameters'] || {}
227 ).inject({}) { |h,(k,v)| h[k]=v; h }).keys
231 # Returns an <code>Array</code> of the required parameters for this
234 # @return [Array] The required parameters.
237 # # A list of all required parameters.
238 # method.required_parameters
239 def required_parameters
240 @required_parameters ||= ((self.parameter_descriptions.select do |k, v|
242 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
246 # Returns an <code>Array</code> of the optional parameters for this
249 # @return [Array] The optional parameters.
252 # # A list of all optional parameters.
253 # method.optional_parameters
254 def optional_parameters
255 @optional_parameters ||= ((self.parameter_descriptions.reject do |k, v|
257 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
261 # Verifies that the parameters are valid for this method. Raises an
262 # exception if validation fails.
264 # @param [Hash, Array] parameters
265 # The parameters to verify.
267 # @return [NilClass] <code>nil</code> if validation passes.
268 def validate_parameters(parameters={})
269 parameters = self.normalize_parameters(parameters)
270 required_variables = ((self.parameter_descriptions.select do |k, v|
272 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
273 missing_variables = required_variables - parameters.map(&:first)
274 if missing_variables.size > 0
276 "Missing required parameters: #{missing_variables.join(', ')}."
278 parameters.each do |k, v|
279 if self.parameter_descriptions[k]
280 enum = self.parameter_descriptions[k]['enum']
281 if enum && !enum.include?(v)
283 "Parameter '#{k}' has an invalid value: #{v}. " +
284 "Must be one of #{enum.inspect}."
286 pattern = self.parameter_descriptions[k]['pattern']
288 regexp = Regexp.new("^#{pattern}$")
291 "Parameter '#{k}' has an invalid value: #{v}. " +
292 "Must match: /^#{pattern}$/."
301 # Returns a <code>String</code> representation of the method's state.
303 # @return [String] The method's state, as a <code>String</code>.
307 self.class.to_s, self.object_id, self.id