Class: GoogleAPI::API

Inherits:
Object
  • Object
show all
Defined in:
lib/google-api/api.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(access_token, api, map) ⇒ API

Returns a new instance of API.



6
7
8
9
10
# File 'lib/google-api/api.rb', line 6

def initialize(access_token, api, map)
  @access_token = access_token
  @api = api
  @map = map
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Taking over #method_missing here allows us to chain multiple methods onto a API instance. If the current place we are in the API includes this method, then let’s call it! If not, and there are multiple methods below this section of the API, build a new API and do it all over again.

As an example:

User.find(1).google.drive.files.list => we will be calling this method twice, once to find all
methods within the files section of the API, and once to send a request to the #list API method,
delegating to the #request method above.

User.find(1).google.drive.files.permissions.list => we will end up calling this method three times,
until we get to the end of the chain.
(Note: This method chain doesn't map to an actual Google Drive API method.)

If the API method includes a mediaUpload key, we know that this method allows uploads, like to upload a new Google Drive file. If so, we call the #upload method instead of #request.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/google-api/api.rb', line 29

def method_missing(method, *args)
  api_method = map[method.to_s]
  args = args.last.is_a?(Hash) ? args.last : {} # basically #extract_options!
  methods_or_resources = api_method['methods'] || api_method['resources']
  if methods_or_resources
    API.new(access_token, api, methods_or_resources)
  else
    url, options = build_url(api_method, args)

    raise ArgumentError, ":body parameter was not passed" if !options[:body] && %w(POST PUT PATCH).include?(api_method['httpMethod'])

    send(api_method['mediaUpload'] && args[:media] ? :upload : :request, api_method['httpMethod'].downcase, url, options)
  end
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



4
5
6
# File 'lib/google-api/api.rb', line 4

def access_token
  @access_token
end

#apiObject (readonly)

Returns the value of attribute api.



4
5
6
# File 'lib/google-api/api.rb', line 4

def api
  @api
end

#mapObject (readonly)

Returns the value of attribute map.



4
5
6
# File 'lib/google-api/api.rb', line 4

def map
  @map
end