Skip to content

Instantly share code, notes, and snippets.

@tgezginis
Created July 25, 2014 18:07
Show Gist options
  • Save tgezginis/fa122249d0b048552703 to your computer and use it in GitHub Desktop.
Save tgezginis/fa122249d0b048552703 to your computer and use it in GitHub Desktop.
RoR Google Analytics Sample
#config/ganalytics.yml
development:
GA_APP_NAME: sample
GA_KEY_FILE_NAME: ganalytics-key-file.p12
GA_SERVICE_ACCOUNT_EMAIL: sample@developer.gserviceaccount.com
production:
GA_APP_NAME: sample
GA_KEY_FILE_NAME: ganalytics-key-file.p12
GA_SERVICE_ACCOUNT_EMAIL: sample@developer.gserviceaccount.com
gem 'google-api-client'
#lib/tasks/google_analytics.rake
require 'json'
namespace :google_analytics do
desc "Get Google Analaytics data and store it in tmp/cache/analytics_data.json"
task get_analytics_data: :environment do
ga = ::GoogleAnalytics.new()
today = Date.today
@visitors_pageviews = ga.date_dimension((today-30).strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d"))
@sources = ga.source_dimension((today-30).strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d"))
@keywords = ga.keyword_dimension((today-30).strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d"))
@locations = ga.location_dimension((today-30).strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d"))
h = {:visitors_pageviews => @visitors_pageviews, :sources => @sources, :keywords => @keywords, :locations => @locations}
tmp_path = File.join("tmp/cache", "analytics_data.json")
File.open(tmp_path,"w") do |f|
f.write(h.to_json)
end
puts "Google Analytics verileri güncellendi. - " + Time.now.strftime("%d.%m.%Y %H:%M:%S")
end
end
#app/services/google_analytics.rb
require 'google/api_client'
require 'date'
class GoogleAnalytics
def initialize
@client = Google::APIClient.new(:application_name => ANALYTICS_API['GA_APP_NAME'], :application_version => '1.0')
key_file = File.join('config', ANALYTICS_API['GA_KEY_FILE_NAME'])
key = Google::APIClient::PKCS12.load_key(key_file, 'notasecret')
service_account = Google::APIClient::JWTAsserter.new(
ANALYTICS_API['GA_SERVICE_ACCOUNT_EMAIL'],
'https://www.googleapis.com/auth/analytics.readonly', key)
@client.authorization = service_account.authorize
@analytics = @client.discovered_api('analytics', 'v3')
end
def date_dimension(startDate, endDate)
results = @client.execute(:api_method => @analytics.data.ga.get, :parameters => {
'ids' => "ga:" + Settings.google_analytics_track_code,
'start-date' => startDate,
'end-date' => endDate,
'metrics' => "ga:users,ga:pageviews,ga:sessions,ga:sessionDuration,ga:bounceRate",
'dimensions' => "ga:year,ga:month,ga:day",
'sort' => "ga:year,ga:month,ga:day"
})
if results.error?
puts results.error_message
return {}
else
hash = Hash.new()
hash["users"] = Hash.new()
hash["pageviews"] = Hash.new()
hash["sessions"] = Hash.new()
hash["sessionDuration"] = Hash.new()
hash["bounceRate"] = Hash.new()
results.data.rows.each do |r|
hash["users"]["#{r[0]}-#{r[1]}-#{r[2]}"] = r[3].to_i
hash["pageviews"]["#{r[0]}-#{r[1]}-#{r[2]}"] = r[4].to_i
hash["sessions"]["#{r[0]}-#{r[1]}-#{r[2]}"] = r[5].to_i
hash["sessionDuration"]["#{r[0]}-#{r[1]}-#{r[2]}"] = r[6].to_i/24
hash["bounceRate"]["#{r[0]}-#{r[1]}-#{r[2]}"] = r[7]
end
return hash
end
end
def source_dimension(startDate, endDate)
results = @client.execute(:api_method => @analytics.data.ga.get, :parameters => {
'ids' => "ga:" + Settings.google_analytics_track_code,
'start-date' => startDate,
'end-date' => endDate,
'metrics' => "ga:users",
'dimensions' => "ga:source",
'sort' => "-ga:users"
})
if results.error?
puts results.error_message
return {}
else
hash = Hash.new()
hash["sources"] = Hash.new()
results.data.rows.each do |r|
hash["sources"]["#{r[0]}"] = r[1].to_i
end
return hash
end
end
def keyword_dimension(startDate, endDate)
results = @client.execute(:api_method => @analytics.data.ga.get, :parameters => {
'ids' => "ga:" + Settings.google_analytics_track_code,
'start-date' => startDate,
'end-date' => endDate,
'metrics' => "ga:sessions",
'dimensions' => "ga:keyword",
'sort' => "-ga:sessions"
})
if results.error?
puts results.error_message
return {}
else
hash = Hash.new()
hash["keywords"] = Hash.new()
results.data.rows.each do |r|
hash["keywords"]["#{r[0]}"] = r[1].to_i
end
return hash
end
end
def location_dimension(startDate, endDate)
results = @client.execute(:api_method => @analytics.data.ga.get, :parameters => {
'ids' => "ga:" + Settings.google_analytics_track_code,
'start-date' => startDate,
'end-date' => endDate,
'metrics' => "ga:sessions",
'dimensions' => "ga:city,ga:country",
'sort' => "-ga:sessions"
})
if results.error?
puts results.error_message
return {}
else
hash = Hash.new()
hash["locations"] = Hash.new()
results.data.rows.each do |r|
hash["locations"]["#{r[0]} - #{r[1]}"] = r[2].to_i
end
return hash
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment