Skip to content

Instantly share code, notes, and snippets.

@nownabe
Created July 8, 2016 02:35
Show Gist options
  • Save nownabe/4d57a6adb79e714174f4bae1bd457529 to your computer and use it in GitHub Desktop.
Save nownabe/4d57a6adb79e714174f4bae1bd457529 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'google/apis/analytics_v3'
require 'google/api_client/auth/key_utils'
module GoogleServices
class Analytics
attr_reader :start_date, :end_date
def initialize(start_date: nil, end_date: nil)
@end_date = end_date || Time.zone.today
@start_date = start_date || @end_date - 1.week
end
def execute
result
end
private
def authorization
@authorization ||=
Signet::OAuth2::Client.new(
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
audience: 'https://accounts.google.com/o/oauth2/token',
scope: Google::Apis::AnalyticsV3::AUTH_ANALYTICS_READONLY,
issuer: issuer,
signing_key: signing_key
)
end
def client
@client ||=
Google::Apis::AnalyticsV3::AnalyticsService.new.tap do |c|
c.client_options.application_name = 'My App'
c.client_options.application_version = '0.1'
c.authorization = authorization
end
end
def column_headers
raw_response.column_headers
end
def header_keys
column_headers.map { |header| header.name.sub('ga:', '') }
end
def issuer
Settings.google_analytics.issuer
end
def key_file
Rails.root.join(Settings.google_analytics.key_file).to_s
end
def key_secret
Settings.google_analytics.key_secret
end
def profile_id
"ga:#{Settings.google_analytics.profile_id}"
end
# https://github.com/google/google-api-ruby-client/blob/0.9.11/generated/google/apis/analytics_v3/service.rb#L113
def raw_response
@raw_response ||=
client.get_ga_data(
profile_id,
start_date.strftime('%Y-%m-%d'),
end_date.strftime('%Y-%m-%d'),
'ga:sessions,ga:pageviews',
dimensions: 'ga:date',
filters: 'ga:pagePath==/',
sort: 'ga:date'
)
end
def result
return @result if @result
return @result = {} if column_headers.nil?
@result =
rows.each_with_object({}) do |row, result|
date_key = Date.parse(row.first).strftime('%Y-%m-%d')
result[date_key] = Hash[[header_keys[1..-1], row[1..-1]].transpose]
end
end
def rows
raw_response.rows
end
def signing_key
Google::APIClient::KeyUtils.load_from_pkcs12(
key_file,
key_secret
)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment