Class: Gattica::Engine

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

Overview

The real meat of Gattica, deals with talking to GA, returning and parsing results. You actually get an instance of this when you go Gattica.new()

Constant Summary collapse

SERVER =
'www.google.com'
PORT =
443
SECURE =
true
DEFAULT_ARGS =
{ :start_date => nil, :end_date => nil, :dimensions => [], :metrics => [], :filters => [], :sort => [] }
DEFAULT_OPTIONS =
{ :email => nil, :password => nil, :token => nil, :profile_id => nil, :debug => false, :headers => {}, :logger => Logger.new(STDOUT) }
FILTER_METRIC_OPERATORS =
%w{ == != > < >= <= }
FILTER_DIMENSION_OPERATORS =
%w{ == != =~ !~ =@ ~@ }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Engine

Create a user, and get them authorized. If you’re making a web app you’re going to want to save the token that’s retrieved by Gattica so that you can use it later (Google recommends not re-authenticating the user for each and every request)

ga = Gattica.new({:email => '[email protected]', :password => 'password', :profile_id => 123456})
ga.token => 'DW9N00wenl23R0...' (really long string)

Or if you already have the token (because you authenticated previously and now want to reuse that session):

ga = Gattica.new({:token => '23ohda09hw...', :profile_id => 123456})


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/gattica.rb', line 65

def initialize(options={})
  @options = DEFAULT_OPTIONS.merge(options)
  @logger = @options[:logger]
  
  @profile_id = @options[:profile_id]     # if you don't include the profile_id now, you'll have to set it manually later via Gattica::Engine#profile_id=
  @user_accounts = nil                    # filled in later if the user ever calls Gattica::Engine#accounts
  @headers = {}.merge(@options[:headers]) # headers used for any HTTP requests (Google requires a special 'Authorization' header which is set any time @token is set)
  
  # save an http connection for everyone to use
  @http = Net::HTTP.new(SERVER, PORT)
  @http.use_ssl = SECURE
  @http.set_debug_output $stdout if @options[:debug]
  
  # authenticate
  if @options[:email] && @options[:password]      # email and password: authenticate, get a token from Google's ClientLogin, save it for later
    @user = User.new(@options[:email], @options[:password])
    @auth = Auth.new(@http, user)
    self.token = @auth.tokens[:auth]
  elsif @options[:token]                          # use an existing token
    self.token = @options[:token]
  else                                            # no login or token, you can't do anything
    raise GatticaError::NoLoginOrToken, 'You must provide an email and password, or authentication token'
  end
  
  # TODO: check that the user has access to the specified profile and show an error here rather than wait for Google to respond with a message
end

Instance Attribute Details

#profile_idObject

Returns the value of attribute profile_id.



52
53
54
# File 'lib/gattica.rb', line 52

def profile_id
  @profile_id
end

#tokenObject

Returns the value of attribute token.



52
53
54
# File 'lib/gattica.rb', line 52

def token
  @token
end

#userObject (readonly)

Returns the value of attribute user.



51
52
53
# File 'lib/gattica.rb', line 51

def user
  @user
end

Instance Method Details

#accountsObject

Returns the list of accounts the user has access to. A user may have multiple accounts on Google Analytics and each account may have multiple profiles. You need the profile_id in order to get info from GA. If you don’t know the profile_id then use this method to get a list of all them. Then set the profile_id of your instance and you can make regular calls from then on.

ga = Gattica.new({:email => '[email protected]', :password => 'password'})
ga.get_accounts
# you parse through the accounts to find the profile_id you need
ga.profile_id = 12345678
# now you can perform a regular search, see Gattica::Engine#get

If you pass in a profile id when you instantiate Gattica::Search then you won’t need to get the accounts and find a profile_id - you apparently already know it!

See Gattica::Engine#get to see how to get some data.



109
110
111
112
113
114
115
116
117
# File 'lib/gattica.rb', line 109

def accounts
  # if we haven't retrieved the user's accounts yet, get them now and save them
  if @user_accounts.nil?
    data = do_http_get('/analytics/feeds/accounts/default')
    xml = Hpricot(data)
    @user_accounts = xml.search(:entry).collect { |entry| Account.new(entry) }
  end
  return @user_accounts
end

#get(args = {}) ⇒ Object

This is the method that performs the actual request to get data.

Usage

gs = Gattica.new({:email => '[email protected]', :password => 'password', :profile_id => 123456})
gs.get({ :start_date => '2008-01-01', 
         :end_date => '2008-02-01', 
         :dimensions => 'browser', 
         :metrics => 'pageviews', 
         :sort => 'pageviews',
         :filters => ['browser == Firefox']})

Input

When calling get you’ll pass in a hash of options. For a description of what these mean to Google Analytics, see code.google.com/apis/analytics/docs

Required values are:

  • start_date => Beginning of the date range to search within

  • end_date => End of the date range to search within

Optional values are:

  • dimensions => an array of GA dimensions (without the ga: prefix)

  • metrics => an array of GA metrics (without the ga: prefix)

  • filter => an array of GA dimensions/metrics you want to filter by (without the ga: prefix)

  • sort => an array of GA dimensions/metrics you want to sort by (without the ga: prefix)

Exceptions

If a user doesn’t have access to the profile_id you specified, you’ll receive an error. Likewise, if you attempt to access a dimension or metric that doesn’t exist, you’ll get an error back from Google Analytics telling you so.



155
156
157
158
159
160
161
162
# File 'lib/gattica.rb', line 155

def get(args={})
  args = validate_and_clean(DEFAULT_ARGS.merge(args))
  query_string = build_query_string(args,@profile_id)
    @logger.debug(query_string) if @debug
  data = do_http_get("/analytics/feeds/data?#{query_string}")
  #data = do_http_get("/analytics/feeds/data?ids=ga%3A915568&metrics=ga%3Avisits&segment=gaid%3A%3A-7&start-date=2010-03-29&end-date=2010-03-29&max-results=50")
  return DataSet.new(Hpricot.XML(data))
end