Class: Google::APIClient::Method

Inherits:
Object
  • Object
show all
Defined in:
lib/google/api_client/discovery/method.rb

Overview

A method that has been described by a discovery document.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api, method_base, method_name, discovery_document) ⇒ Google::APIClient::Method

Creates a description of a particular method.

Parameters:

  • api (Google::APIClient::API)

    The API this method belongs to.

  • method_base (Addressable::URI)

    The base URI for the service.

  • method_name (String)

    The identifier for the method.

  • method_description (Hash)

    The section of the discovery document that applies to this method.



41
42
43
44
45
46
# File 'lib/google/api_client/discovery/method.rb', line 41

def initialize(api, method_base, method_name, discovery_document)
  @api = api
  @method_base = method_base
  @name = method_name
  @discovery_document = discovery_document
end

Instance Attribute Details

#apiGoogle::APIClient::API (readonly)

Returns the API this method belongs to.

Returns:



52
53
54
# File 'lib/google/api_client/discovery/method.rb', line 52

def api
  @api
end

#descriptionHash (readonly)

Returns the parsed section of the discovery document that applies to this method.

Returns:

  • (Hash)

    The method description.



65
66
67
# File 'lib/google/api_client/discovery/method.rb', line 65

def description
  @description
end

#method_baseAddressable::URI

Returns the base URI for the method.

Returns:

  • (Addressable::URI)

    The base URI that this method will be joined to.



72
73
74
# File 'lib/google/api_client/discovery/method.rb', line 72

def method_base
  @method_base
end

#nameString (readonly)

Returns the identifier for the method.

Returns:

  • (String)

    The method identifier.



58
59
60
# File 'lib/google/api_client/discovery/method.rb', line 58

def name
  @name
end

Instance Method Details

#generate_request(parameters = {}, body = '', headers = [], options = {}) ⇒ Array

Generates an HTTP request for this method.

Parameters:

  • parameters (Hash, Array) (defaults to: {})

    The parameters to send.

  • body (String, StringIO) (defaults to: '')

    The body for the HTTP request.

  • headers (Hash, Array) (defaults to: [])

    The HTTP headers for the request.

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :connection (Faraday::Connection)

    The HTTP connection to use.

Returns:

  • (Array)

    The generated HTTP request.



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/google/api_client/discovery/method.rb', line 225

def generate_request(parameters={}, body='', headers=[], options={})
  options[:connection] ||= Faraday.default_connection
  if body.respond_to?(:string)
    body = body.string
  elsif body.respond_to?(:to_str)
    body = body.to_str
  else
    raise TypeError, "Expected String or StringIO, got #{body.class}."
  end
  if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
    raise TypeError, "Expected Hash or Array, got #{headers.class}."
  end
  method = self.http_method
  uri = self.generate_uri(parameters)
  headers = headers.to_a if headers.kind_of?(Hash)
  return options[:connection].build_request(
    method.to_s.downcase.to_sym
  ) do |req|
    req.url(Addressable::URI.parse(uri).normalize.to_s)
    req.headers = Faraday::Utils::Headers.new(headers)
    req.body = body
  end
end

#generate_uri(parameters = {}) ⇒ Addressable::URI

Expands the method’s URI template using a parameter list.

Parameters:

  • parameters (Hash, Array) (defaults to: {})

    The parameter list to use.

Returns:

  • (Addressable::URI)

    The URI after expansion.



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/google/api_client/discovery/method.rb', line 183

def generate_uri(parameters={})
  parameters = self.normalize_parameters(parameters)
  self.validate_parameters(parameters)
  template_variables = self.uri_template.variables
  upload_type = parameters.assoc('uploadType') || parameters.assoc('upload_type')
  if upload_type
    unless self.media_upload
      raise ArgumentException, "Media upload not supported for this method"
    end
    case upload_type.last
    when 'media', 'multipart', 'resumable'
      uri = self.media_upload.uri_template.expand(parameters)
    else
      raise ArgumentException, "Invalid uploadType '#{upload_type}'"
    end
  else
    uri = self.uri_template.expand(parameters)
  end
  query_parameters = parameters.reject do |k, v|
    template_variables.include?(k)
  end
  # encode all non-template parameters
  params = ""
  unless query_parameters.empty?
    params = "?" + Addressable::URI.form_encode(query_parameters.sort)
  end
  # Normalization is necessary because of undesirable percent-escaping
  # during URI template expansion
  return uri.normalize + params
end

#http_methodString

Returns the HTTP method or ‘GET’ if none is specified.

Returns:

  • (String)

    The HTTP method that will be used in the request.



96
97
98
# File 'lib/google/api_client/discovery/method.rb', line 96

def http_method
  return @discovery_document['httpMethod'] || 'GET'
end

#idString

Returns the method ID.

Returns:

  • (String)

    The method identifier.



88
89
90
# File 'lib/google/api_client/discovery/method.rb', line 88

def id
  return @discovery_document['id']
end

#inspectString

Returns a String representation of the method’s state.

Returns:

  • (String)

    The method’s state, as a String.



361
362
363
364
365
366
# File 'lib/google/api_client/discovery/method.rb', line 361

def inspect
  sprintf(
    "#<%s:%#0x ID:%s>",
    self.class.to_s, self.object_id, self.id
  )
end

#media_uploadGoogle::APIClient::MediaUpload

Returns media upload information for this method, if supported

Returns:



115
116
117
118
119
120
121
# File 'lib/google/api_client/discovery/method.rb', line 115

def media_upload
  if @discovery_document['mediaUpload']
    return @media_upload ||= Google::APIClient::MediaUpload.new(self, self.method_base, @discovery_document['mediaUpload'])
  else
    return nil
  end
end

#normalize_parameters(parameters = {}) ⇒ Hash

Normalizes parameters, converting to the appropriate types.

Parameters:

  • parameters (Hash, Array) (defaults to: {})

    The parameters to normalize.

Returns:

  • (Hash)

    The normalized parameters.



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/google/api_client/discovery/method.rb', line 156

def normalize_parameters(parameters={})
  # Convert keys to Strings when appropriate
  if parameters.kind_of?(Hash) || parameters.kind_of?(Array)
    # Returning an array since parameters can be repeated (ie, Adsense Management API)
    parameters = parameters.inject([]) do |accu, (k, v)|
      k = k.to_s if k.kind_of?(Symbol)
      k = k.to_str if k.respond_to?(:to_str)
      unless k.kind_of?(String)
        raise TypeError, "Expected String, got #{k.class}."
      end
      accu << [k, v]
      accu
    end
  else
    raise TypeError,
      "Expected Hash or Array, got #{parameters.class}."
  end
  return parameters
end

#optional_parametersArray

Returns an Array of the optional parameters for this method.

Examples:

# A list of all optional parameters.
method.optional_parameters

Returns:

  • (Array)

    The optional parameters.



295
296
297
298
299
# File 'lib/google/api_client/discovery/method.rb', line 295

def optional_parameters
  @optional_parameters ||= ((self.parameter_descriptions.reject do |k, v|
    v['required']
  end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
end

#parameter_descriptionsHash

Returns a Hash of the parameter descriptions for this method.

Returns:

  • (Hash)

    The parameter descriptions.



255
256
257
258
259
# File 'lib/google/api_client/discovery/method.rb', line 255

def parameter_descriptions
  @parameter_descriptions ||= (
    @discovery_document['parameters'] || {}
  ).inject({}) { |h,(k,v)| h[k]=v; h }
end

#parametersArray

Returns an Array of the parameters for this method.

Returns:

  • (Array)

    The parameters.



265
266
267
268
269
# File 'lib/google/api_client/discovery/method.rb', line 265

def parameters
  @parameters ||= ((
    @discovery_document['parameters'] || {}
  ).inject({}) { |h,(k,v)| h[k]=v; h }).keys
end

#request_schemaGoogle::APIClient::Schema

Returns the Schema object for the method’s request, if any.

Returns:



127
128
129
130
131
132
133
134
# File 'lib/google/api_client/discovery/method.rb', line 127

def request_schema
  if @discovery_document['request']
    schema_name = @discovery_document['request']['$ref']
    return @api.schemas[schema_name]
  else
    return nil
  end
end

#required_parametersArray

Returns an Array of the required parameters for this method.

Examples:

# A list of all required parameters.
method.required_parameters

Returns:

  • (Array)

    The required parameters.



280
281
282
283
284
# File 'lib/google/api_client/discovery/method.rb', line 280

def required_parameters
  @required_parameters ||= ((self.parameter_descriptions.select do |k, v|
    v['required']
  end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
end

#response_schemaGoogle::APIClient::Schema

Returns the Schema object for the method’s response, if any.

Returns:



140
141
142
143
144
145
146
147
# File 'lib/google/api_client/discovery/method.rb', line 140

def response_schema
  if @discovery_document['response']
    schema_name = @discovery_document['response']['$ref']
    return @api.schemas[schema_name]
  else
    return nil
  end
end

#uri_templateAddressable::Template

Returns the URI template for the method. A parameter list can be used to expand this into a URI.

Returns:

  • (Addressable::Template)

    The URI template.



105
106
107
108
109
# File 'lib/google/api_client/discovery/method.rb', line 105

def uri_template
  return @uri_template ||= Addressable::Template.new(
    self.method_base.join(Addressable::URI.parse(@discovery_document['path']))
  )
end

#validate_parameters(parameters = {}) ⇒ NilClass

Verifies that the parameters are valid for this method. Raises an exception if validation fails.

Parameters:

  • parameters (Hash, Array) (defaults to: {})

    The parameters to verify.

Returns:

  • (NilClass)

    nil if validation passes.



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/google/api_client/discovery/method.rb', line 309

def validate_parameters(parameters={})
  parameters = self.normalize_parameters(parameters)
  required_variables = ((self.parameter_descriptions.select do |k, v|
    v['required']
  end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
  missing_variables = required_variables - parameters.map { |(k, _)| k }
  if missing_variables.size > 0
    raise ArgumentError,
      "Missing required parameters: #{missing_variables.join(', ')}."
  end
  parameters.each do |k, v|
    # Handle repeated parameters.
    if self.parameter_descriptions[k] &&
        self.parameter_descriptions[k]['repeated'] &&
        v.kind_of?(Array)
      # If this is a repeated parameter and we've got an array as a
      # value, just provide the whole array to the loop below.
      items = v
    else
      # If this is not a repeated parameter, or if it is but we're
      # being given a single value, wrap the value in an array, so that
      # the loop below still works for the single element.
      items = [v]
    end

    items.each do |item|
      if self.parameter_descriptions[k]
        enum = self.parameter_descriptions[k]['enum']
        if enum && !enum.include?(item)
          raise ArgumentError,
            "Parameter '#{k}' has an invalid value: #{item}. " +
            "Must be one of #{enum.inspect}."
        end
        pattern = self.parameter_descriptions[k]['pattern']
        if pattern
          regexp = Regexp.new("^#{pattern}$")
          if item !~ regexp
            raise ArgumentError,
              "Parameter '#{k}' has an invalid value: #{item}. " +
              "Must match: /^#{pattern}$/."
          end
        end
      end
    end
  end
  return nil
end