Reputation: 882
My website built on Rails 4.0.3 uses the google-api-client
gem to authenticate and query the Google Analytics API for analytics data.
I use this analytics data to build simple sparklines for my blog posts.
The data I am querying constitutes pageviews for a period of 30 days.
To that end, I have organized my code into a helper file and a model. I am not sure if this the correct approach, because when I load my admin page, it slows down to a crawl.
pageviews.rb
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
result = client.execute(:api_method => analytics.management.profiles.list, parameters: parameters)
profiles = result.data.items
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}"
}
result = client.execute(:api_method => analytics.data.ga.get, :parameters => parameters)
interim = result.data.rows.map{|hit| hit[1].to_i}.join(', ')
end
end
reporting_helper.rb
require 'google/api_client'
require 'date'
module ReportingHelper
SERVICE_ACCOUNT_EMAIL = 'my_email'
KEY_PATH = File.join(Rails.root, '/config/', 'mykey.p12')
PROFILE = 'ga:123456'
def self.initclient
client = Google::APIClient.new(:application_name => 'rishighan.com', :application_version => '1')
key = Google::APIClient::PKCS12.load_key(KEY_PATH, 'notafoo')
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
I am using an array.map
method to extract values out of the response and then using join
to create a comma-separated sequence of integers for the sparklines plugin to use.
I know that this operation is expensive and is the one at fault for slowing the page down.
I want to know if there is a right way to handle these expensive API requests.
Thank you in advance.
Upvotes: 1
Views: 244
Reputation: 1895
Performing a new API request to Google is very expensive!
You should use low level caching Rails.cache.fetch
to cache the API data.
You could even use a worker to asynchronously send API calls, so your service won't be slowed down.
Upvotes: 1