Google Api 
Analytics - v1.0.0
Calendar - will be soon
Google Analytics
News
For now is released beta version. Pleas use issues for problems.
Installation
Add this line to your application's Gemfile:
gem 'google_api'
And then execute:
$ bundle
Or install it yourself as:
$ gem install google_api
Configuration
First you must create project at google console.
GoogleApi.configure do
client_id "1"
ga do
client_id "2"
end
end
# ----- OR -----
GoogleApi.config.client_id = "4"
GoogleApi.config.ga.client_id = "5"
| name | example | note |
|---|---|---|
| client_id | 123456.apps.googleusercontent.com | required for oauth 2 |
| client_secret | 123456123456123456 | |
| redirect_uri | http://localhost/oauth2callback | |
| client_developer_email | [email protected] | required for login by cert |
| client_cert_file | /home/user/app/123456-privatekey.p12 | |
| key_secret | notasecret | |
| only for ga | ||
| cache | default: GoogleApi::Cache.new | more information Cache |
Cache
Cache must have these methods:
write(key, value, expire) - expire=0 for never expire
read(key)
exists?(key)
delete(key)
Session
There is a 3 way for starting sesssion. Client login with username and password is deprecated.
By cert file
First you must add your developer email to google analytics profile.
# try login once
GoogleApi::Ga::Session.login_by_cert
# ----- OR -----
# trying login in loop
GoogleApi::Ga::Session.login_by_cert!
By oauth 2
# return uri for oauth 2 login
GoogleApi::Ga::Session.login
# after callback
# code = code key in query (params[:code])
GoogleApi::Ga::Session.login(code)
In rails:
redirect_to(GoogleApi::Ga::Session.login)
# in page specified in redirect_uri
GoogleApi::Ga::Session.login(params[:code])
By oauth 2 via line (browser needed)
This will create TCPServer. After login will be closed.
server: optional is localhost, must be full path!
port: on which port the server will listen
# default:
# server = http://localhost/oauth2callback
# port = 0 - get first free port
GoogleApi::Ga::Session.login_by_line(server, port)
Management
| Account ~~~ Webproperty ~~~ Profile ~~~ Goal ~~~ Segment | |
|---|---|
| all | find all |
| find(id) | find one by id |
| refresh | refresh data |
Account
# Variables: id, name, created, updated
# Methods: webproperties
GoogleApi::Ga::Account
Webproperty
# Variables: id, name, created, updated, accountId, websiteUrl
# Methods: account, profiles
GoogleApi::Ga::Webproperty
Profile
# Variables: id, name, created, updated, accountId, websiteUrl, currency, timezone
# Methods: webproperty, goals
GoogleApi::Ga::Profile
Goal
# Variables: accountId, webPropertyId, profileId, value, active, type, goal
# Methods: profile
GoogleApi::Ga::Goal
Segment
# Variables: id, name, created, updated, segmentId, definition
GoogleApi::Ga::Segment
Set default id
GoogleApi::Ga.id(123456) # profile id
Data
First you can play on the playground: http://ga-dev-tools.appspot.com/explorer/.
GoogleApi::Ga::Data
| method name | alias |
|---|---|
| ids | id |
| start_date | from |
| end_date | to |
| metrics | select |
| dimensions | with |
| sort | |
| filters | where |
| segment | |
| start_index | offset |
| max_results | offset |
ids
doc: doc
Id of profile, by default is use id from GoogleApi::Ga.id.
start_date, end_date
doc: start-date, end-date
default: Date.today
parameters:
String in YYYY-MM-DD or Date or DateTime or Time
Integer for add or sub days from Date.today
metrics, dimensions, sort
doc: metrics, dimensions, sort
you can also add or sub parameters with
.method_addor.method_subparameters: Array with String or Symbol, String (not compiled, "ga:visitors") or Symbol (compiled, :visitors)
filters, segment
parameters:
operator value) & (attribute operator value) | (attribute operator value) or String (not compiled)operators: ==, !=, >, <, >=, <=, =~, !~
% is =@
** is !@
start_index
doc: start-index
parameters: Integer from 1.
max_results
doc: max-results
parameters: Integer from 1 to 10 000.
Cache
For how long in minutes will be data cached. Use 0 for never expire.
GoogleApi::Ga::Data.cache(minutes)
# you can also clear cache
GoogleApi::Ga::Data.clear_cache
# if you want clear cache and cache new
GoogleApi::Ga::Data.select(:visits).clear_cache.cache(60)
# orif you don't want use cache at all, default: true
GoogleApi::Ga::Data.use_cache(false)
Error
What happen if parameters are wrong.
# raise error with message
GoogleApi::Ga::Data.error(true)
# default, not raise error, just empty result
GoogleApi::Ga::Data.error(false)
Fetch data
You can use one of these. Data is stored in the class.
.all # [header, rows]
.rows # rows returned by google analytics
.header # header of data, (["ga:day", "ga:month", "ga:visitis"])
.count # number of rows
.each # each as you expected, (`|data|` or `|index, data|`)
Clear stored data and fetch again
If you add some parameters clear is called automaticlly.
clear: .clear
clear and fetch new:
.all!, .rows!, .header!, .count!, .each!
Examples
# Start session
# =============
# set configuration
GoogleApi.config.ga.client_cert_file = "privatekey.p12"
GoogleApi.config.ga.client_developer_email = "[email protected]"
# start session
GoogleApi::Ga::Session.login_by_cert!
# Get profile id
# ==============
# get profile id
id = GoogleApi::Ga::Profile.all.first.id
# set default id
GoogleApi::Ga.id(id)
# Starting session by line
# ========================
# First install launchy:
# gem install launchy
# callback_uri and port are optional - auto start server at localhost
GoogleApi::Ga::Session.login_by_line(callback_uri, port)
# This will do
# 1) create server
# 2) launch browser and redirect to google api
# 3) confirm and google api redirect to localhost
# 4) server get code and start session
# 5) close server - you are login
# Check session, error if not login
# =================================
GoogleApi::Ga::Session.check_session!
# Management of accounts
# ======================
# all accounts
accounts = GoogleApi::Ga::Account.all
# webproperties for account
accounts.first.webproperties
# all webproperties
GoogleApi::Ga::Webproperty.all
# all profiles
GoogleApi::Ga::Profile.all
# all goal
GoogleApi::Ga::Goal.all
# all segment
GoogleApi::Ga::Segment.all
# Count of visitors between previous month and today
# ==================================================
GoogleApi::Ga::Data.from(-30).select(:visits).rows
# Count of visitors between previous month and today - 2, and cache it for 30 minutes
# ===================================================================================
GoogleApi::Ga::Data.from(-30).to(-2).select(:visits).cache(30).rows
# Visitors by day, month, year from Czech Republic. Browser is Firefox and Opera or Chrome
# ========================================================================================
GoogleApi::Ga::Data.from(-30).select(:visits).with(:day, :month, :year)
.sort(:year, :month, :day)
.where{(country == "Czech Republic") &
(browser == "Firefox") &
(browser == "Opera") |
(browser == "Chrome")}
.rows
# ----- OR -----
GoogleApi::Ga::Data.from(-30).select(:visits).with(:day, :month, :year)
.sort(:year, :month, :day)
.where("ga:country==Czech Republic;ga:browser==Firefox;ga:browser==Opera,ga:browser==Chrome")
.rows