Ruby で Google Analytics から直近1時間のページビューランキングを取得する方法
サイトのアクセスランキングを作る方法はいろいろありますが、自前で HTTPサーバのログから計算するのは大変です。Google Analytics の API を使うとアクセス数が Ruby には Google Analytics API を操作できる Garb という便利なラッパーライブラリがあります。今回はこれを使います。 Garbのインストール gemで入れます。プロジェクトは GitHub で管理されています。 https://github.com/vigetlabs/garb # gem install garb Fetching: crack-0.3.1.gem (100%) Fetching: i18n-0.6.1.gem (100%) Fetching: activesupport-3.2.8.gem (100%) Fetching: garb-0.9.1.gem (100%) Successfully installed crack-0.3.1 Successfully installed i18n-0.6.1 Successfully installed activesupport-3.2.8 Successfully installed garb-0.9.1 4 gems installed スクリプト本体 それほど長くないので、まずソースコードを貼っておきます。 #!/usr/bin/ruby1.9.1 # coding: utf-8 require ‘rubygems’ require ‘garb’ require ‘uri’ Garb::Session.login(’<アカウント>’, ‘<パスワード>’) profile = Garb::Management::Profile.all.detect { |p| p.web_property_id = ‘<サイトプロパティID>’ p.id = ‘<アカウントID>’ } class PageTitle extend Garb::Model metrics :pageviews dimensions :hour, :page_path, :page_title end today = Time.now - 3600; start_date = today end_date = today hour = today.hour if hour < 10 hour = “0” + hour.to_s else hour = hour.to_s end cond = { :limit => 20, :sort => :pageviews.desc, :start_date => start_date, :end_date => end_date, :filters => { :hour.eql => hour } } rs = PageTitle.results(profile, cond) rs.each do |r| puts r.page_path # ページパス puts r.page_title # ページタイトル puts r.pageviews # ページビュー end ...