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.

  • discovery_document (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:



55
56
57
# File 'lib/google/api_client/discovery/method.rb', line 55

def api
  @api
end

#discovery_documentString (readonly)

Returns unparsed discovery document for the method.

Returns:

  • (String)

    unparsed discovery document for the method



49
50
51
# File 'lib/google/api_client/discovery/method.rb', line 49

def discovery_document
  @discovery_document
end

#method_baseAddressable::URI

Returns the base URI for the method.

Returns:

  • (Addressable::URI)

    The base URI that this method will be joined to.



68
69
70
# File 'lib/google/api_client/discovery/method.rb', line 68

def method_base
  @method_base
end

#nameString (readonly)

Returns the identifier for the method.

Returns:

  • (String)

    The method identifier.



61
62
63
# File 'lib/google/api_client/discovery/method.rb', line 61

def name
  @name
end

Instance Method Details

#descriptionHash

Returns a human-readable description of the method.

Returns:

  • (Hash)

    The API description.



84
85
86
# File 'lib/google/api_client/discovery/method.rb', line 84

def description
  return @discovery_document['description']
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

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.



232
233
234
235
236
237
238
239
240
# File 'lib/google/api_client/discovery/method.rb', line 232

def generate_request(parameters={}, body='', headers={}, options={})
  if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
    raise TypeError, "Expected Hash or Array, got #{headers.class}."
  end
  method = self.http_method.to_s.downcase.to_sym
  uri = self.generate_uri(parameters)
  headers = Faraday::Utils::Headers.new(headers)
  return [method, uri, headers, body]
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

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.



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
213
214
215
216
217
218
# File 'lib/google/api_client/discovery/method.rb', line 188

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.



100
101
102
# File 'lib/google/api_client/discovery/method.rb', line 100

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

#idString

Returns the method ID.

Returns:

  • (String)

    The method identifier.



92
93
94
# File 'lib/google/api_client/discovery/method.rb', line 92

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.



355
356
357
358
359
360
# File 'lib/google/api_client/discovery/method.rb', line 355

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:



119
120
121
122
123
124
125
# File 'lib/google/api_client/discovery/method.rb', line 119

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.



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/google/api_client/discovery/method.rb', line 160

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.



288
289
290
291
292
# File 'lib/google/api_client/discovery/method.rb', line 288

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.



248
249
250
251
252
# File 'lib/google/api_client/discovery/method.rb', line 248

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.



258
259
260
261
262
# File 'lib/google/api_client/discovery/method.rb', line 258

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:



131
132
133
134
135
136
137
138
# File 'lib/google/api_client/discovery/method.rb', line 131

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.



273
274
275
276
277
# File 'lib/google/api_client/discovery/method.rb', line 273

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:



144
145
146
147
148
149
150
151
# File 'lib/google/api_client/discovery/method.rb', line 144

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.



109
110
111
112
113
# File 'lib/google/api_client/discovery/method.rb', line 109

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

#validate_parameters(parameters = {}) ⇒ NilClass

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

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.



303
304
305
306
307
308
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
# File 'lib/google/api_client/discovery/method.rb', line 303

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