Class: SimpleAnalytics::Api

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

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Api) initialize(username, password, options = {})

Returns a new instance of Api



26
27
28
29
30
# File 'lib/simple_analytics.rb', line 26

def initialize(username, password, options = {})
  @username = username
  @password = password
  @options = options
end

Instance Attribute Details

- (Object) auth_token

An authentication token for the Google Analytics Api.



13
14
15
# File 'lib/simple_analytics.rb', line 13

def auth_token
  @auth_token
end

- (Object) body (readonly)

rows is a 2-dimensional array of strings, each string represents a value in the table. body is the data in response body.



17
18
19
# File 'lib/simple_analytics.rb', line 17

def body
  @body
end

- (Object) rows (readonly)

rows is a 2-dimensional array of strings, each string represents a value in the table. body is the data in response body.



17
18
19
# File 'lib/simple_analytics.rb', line 17

def rows
  @rows
end

Class Method Details

+ (Object) authenticate(username, password, options = {})

Authentication using ClientLogin, returns an analytics service object.



20
21
22
23
24
# File 'lib/simple_analytics.rb', line 20

def self.authenticate(username, password, options = {})
  new(username, password, options).tap do |analytics|
    analytics.authenticate
  end
end

Instance Method Details

- (Object) authenticate

Authenticates using ClientLogin.



33
34
35
36
37
# File 'lib/simple_analytics.rb', line 33

def authenticate
   = ::GoogleClientLogin::GoogleAuth.new(client_options)
  .authenticate(@username, @password, @options[:captcha_response])
  @auth_token = .auth
end

- (Object) fetch(properties)

Fetches the report data, the following query parameters are required: 'ids', 'start-date', 'end-date', 'metrics'.



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/simple_analytics.rb', line 40

def fetch(properties)
  check_properties(properties)

  uri = URI.parse("https://www.googleapis.com/analytics/v3/data/ga")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  response = http.get("#{uri.path}?#{query_string(properties)}", { 'Authorization' => "GoogleLogin auth=#{@auth_token}", 'GData-Version' => '3' })
  raise NotSuccessfulResponseError.new, response.body if response.code_type != Net::HTTPOK
  @body = JSON.parse(response.body)
  @rows = @body['rows']
end