Class: GAShikomi::Api

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

Defined Under Namespace

Classes: InexpectantResponse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(store) ⇒ Api

param

String store



14
15
16
17
18
19
20
# File 'lib/ga_shikomi/api.rb', line 14

def initialize(store)
  @client       = nil
  @analytics    = nil
  @last_request = nil

  init_and_auth_analytics(store)
end

Instance Attribute Details

#analyticsObject (readonly)

Returns the value of attribute analytics.



21
22
23
# File 'lib/ga_shikomi/api.rb', line 21

def analytics
  @analytics
end

#clientObject (readonly)

Returns the value of attribute client.



21
22
23
# File 'lib/ga_shikomi/api.rb', line 21

def client
  @client
end

#last_requestObject (readonly)

Returns the value of attribute last_request.



21
22
23
# File 'lib/ga_shikomi/api.rb', line 21

def last_request
  @last_request
end

Instance Method Details

#execute(method, params = {}) ⇒ Object

param

Object method

return

Hash



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ga_shikomi/api.rb', line 54

def execute(method, params = {})
  @last_request = client.execute(
                    :api_method => method,
                    :parameters => params)

  result = JSON.parse(last_request.response.body)
  if result['error']
    raise InexpectantResponse, result['error']
  else
    result
  end
end

#init_and_auth_analytics(store) ⇒ Object

param

String store



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ga_shikomi/api.rb', line 26

def init_and_auth_analytics(store)
  @client = ::Google::APIClient.new(
                                :application_name    => :gacli,
                                :application_version => VERSION)

  credential = ::Google::APIClient::FileStorage.new(store)
  secrets    = ::Google::APIClient::ClientSecrets.load(File.dirname(store))

  if credential.authorization.nil?
    flow = ::Google::APIClient::InstalledAppFlow.new(
      :client_id     => secrets.client_id,
      :client_secret => secrets.client_secret,
      :scope         => ['https://www.googleapis.com/auth/analytics',
                         'https://www.googleapis.com/auth/analytics.edit'])

    client.authorization = flow.authorize
    credential.write_credentials(client.authorization)
  else
    client.authorization = credential.authorization
  end

  @analytics = client.discovered_api('analytics', 'v3')
end