Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Simple google api. There are: google analytics.
Ruby
tag: v1.0.2

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
.gitignore
.rspec
.travis.yml
CHANGELOG.md
Gemfile
LICENSE
README.md
Rakefile
google_api.gemspec

README.md

Google Api Build Status

Analytics - v1.0.0
Calendar - will be soon

Google Analytics

examples

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 123456@developer.gserviceaccount.com 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


ids

doc

alias: id

Id of profile, by default is use id from GoogleApi::Ga.id.


start_date

doc

alias: from

default: Date.today
parameters:
   String in YYYY-MM-DD or Date or DateTime or Time
   Integer for add or sub days from Date.today


end_date

doc

alias: from

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

doc

required parameters

alias: select

you can also add or sub parameters with .metrics_add or .metrics_sub

parameters: Array with String or Symbol, String (not compiled, "ga:visitors") or Symbol (compiled, :visitors)


dimensions

doc

alias: with

you can also add or sub parameters with .dimensions_add or .dimensions_sub

parameters: Array with String or Symbol, String (not compiled, "ga:visitors") or Symbol (compiled, :visitors)


sort

doc you can also add or sub parameters with .sort_add or .sort_sub

parameters: Array with String or Symbol, String (not compiled, "ga:visitors") or Symbol (compiled, :visitors)


filters

doc

alias: where

parameters:
{(attribute operator value) & (attribute operator value) | (attribute operator value)} or String (not compiled)

operators: ==, !=, >, <, >=, <=, =~, !~
%     is  =@
**     is   !@


segment

doc

parameters:
{(attribute operator value) & (attribute operator value) | (attribute operator value)} or String (not compiled)
with {} automaticly add "dynamic::"

operators: ==, !=, >, <, >=, <=, =~, !~
%     is  =@
**     is   !@


start_index

doc

alias: offset

parameters: Integer from 1.


max_results

doc

alias: limit

parameters: Integer from 1 to 10 000.




cache

For how long in minutes will be data cached. Use 0 for never expire.


clear

Clear stored data.

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 = "123456@developer.gserviceaccount.com"

  # 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
Something went wrong with that request. Please try again.