-追記-
Google API Clientを使う方法を追加しました。
Google Analytics のデータをRubyで取得 (Google API Clientを利用)
-/-
Garbを使う
https://github.com/vigetlabs/garb
Googleが提供しているRuby用ライブラリのページには
http://code.google.com/p/google-api-ruby-client/#Google_Analytics_API
Status: This library is currently alpha and under active development. Don’t use it in critical applications just yet!
と書かれているのでこれは使わずにGarbを使う。
下記は、前月の特定のページ(/items/以下)のタイトルとユニークページビューを
ユニークページビューが多い順に20件取得して表示するサンプル。
備考
・アカウントのID等の情報は、YAMLで読み込んでいる
・日付の設定は、active_supportを使っている
get_unique_pageview.rb
\# coding: utf-8
require ‘rubygems’
require ‘garb’
require ‘uri’
require ‘active_support/time’
require ‘yaml’
#設定読み込み
f = File.open(‘conf.yml’)
conf_str = f.read
myconf = YAML.load(conf_str)
#先月の初め
start\_date = (1.month.ago Time.now).beginning\_of_month
#先月の終わり
end\_date = (1.month.ago Time.now).end\_of_month
Garb::Session.login(
myconf\[‘ga’\]\[‘google_id’\],
myconf\[‘ga’\]\[‘google_pw’\]
)
profile = Garb::Management::Profile.all.detect { |p|
p.web\_property\_id = myconf\[‘ga’\]\[‘property_id’\]
p.id = myconf\[‘ga’\]\[‘profile_id’\]
}
\# 指標とディメンションをGarb::Modelをextendしたクラスに定義
class PageTitle
extend Garb::Model
metrics :unique_pageviews
dimensions :hour, :page\_path, :page\_title
end
cond = {
:limit => 20,
:sort => :unique_pageviews.desc,
:start\_date => start\_date,
:end\_date => end\_date,
:filters => { :page_path.contains => ‘^/items/’ }
}
rs = PageTitle.results(profile, cond)
rs.each do |r|
puts r.page_path # ページパス
puts r.page_title # ページタイトル
puts r.unique_pageviews # ページビュー
end
conf.yml
ga:
google_id : メールアドレスを記入
google_pw : パスワードを記入
property_id : プロパティIDを記入 (UA-XXXXXXXX-X)
profile_id : プロファイルIDを記入 (XXXXXXXX)
参考
rubyのGoogleアナリティクスAPI用ラッパーライブラリ「garb」が面白い
http://web-analytics-or-die.org/2011/12/garb/
Ruby で Google Analytics から直近1時間のページビューランキングを取得する方法
http://d.hatena.ne.jp/tilfin/20120905/1346807962
Google Analyticsデータ取得Gem「Garb」の使い方
http://tsuchikazu.net/googel_analytics_gar/
各言語 ライブラリ一覧
Core Reporting API Client Libraries & Sample Code (v3)
https://developers.google.com/analytics/devguides/reporting/core/v3/gdataLibraries