Last active
October 31, 2016 06:33
-
-
Save rishighan/dc63d225e1ef63ce72e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Pageviews < ActiveRecord::Base | |
#google analytics api shenanigans | |
require 'google/api_client' | |
require 'date' | |
include ReportingHelper | |
def self.getviews post | |
client, analytics, parameters = ReportingHelper.initclient | |
parameters = { | |
'ids' => PROFILE, | |
'start-date' => (Date.today - 30).strftime("%Y-%m-%d"), | |
'end-date' => Date.today.strftime("%Y-%m-%d"), | |
'metrics' => "ga:pageviews", | |
'dimensions' => "ga:date", | |
'filters' => "ga:pagePath=~/#{post}" | |
} | |
cache_key = post #just for debugging. This is unique for each post. | |
# Rails.cache.fetch('google_analytics_api/#{cache_key}', expires_in: 2.minutes) do | |
# result = client.execute(:api_method => analytics.data.ga.get, :parameters => parameters) | |
# result.data.rows.map{|hit| hit[1].to_i}.join(', ') | |
# end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'google/api_client' | |
require 'date' | |
module ReportingHelper | |
SERVICE_ACCOUNT_EMAIL = 'email' | |
KEY_PATH = File.join(Rails.root, '/config/', 'key.p12') | |
PROFILE = 'ga:123456789' | |
def self.initclient | |
client = Google::APIClient.new(:application_name => 'domain.com', :application_version => '1') | |
key = Google::APIClient::PKCS12.load_key(KEY_PATH, 'notasecret') | |
service_account = Google::APIClient::JWTAsserter.new( | |
SERVICE_ACCOUNT_EMAIL, | |
['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/prediction'], | |
key) | |
client.authorization = service_account.authorize | |
analytics = client.discovered_api('analytics', 'v3') | |
parameters = { | |
'accountId' => '~all', | |
'webPropertyId' => '~all' | |
} | |
return client, analytics, parameters | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%div.left-meta | |
=Pageviews.getviews(@post.friendly_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment