Skip to content

Instantly share code, notes, and snippets.

@amichal
Last active March 27, 2017 18:46
Show Gist options
  • Save amichal/bd4f5e1a69b95481998b42bcffdc6e28 to your computer and use it in GitHub Desktop.
Save amichal/bd4f5e1a69b95481998b42bcffdc6e28 to your computer and use it in GitHub Desktop.
Server-side Google Analytics tracking in rails
class ApplicationController
around_filter :track_with_google_analytics
private def track_with_google_analytics
start = Time.now
yield
# Track API hits server-side using Google's Measurement Protocol
# https://developers.google.com/analytics/devguides/collection/protocol/v1/
if ENV['GA_TRACKING_CODE'].present?
finish = Time.now
dl = request.base_url + request.path_info
safe_params = request.query_parameters.except('access_token')
if safe_params.any?
dl += '?' + safe_params.to_query
end
uid = current_resource_owner.try(:id)
aid = current_application.try(:id)
an = current_application.try(:name)
# not needed since we send UID
cid = uid # or by app/user combo? [aid, uid].join('.')
cg1 = "#{controller_path}/#{action_name}"
srt = ((finish-start)*1000).to_i
ul = if request.env['HTTP_ACCEPT_LANGUAGE']
request.env['HTTP_ACCEPT_LANGUAGE'].split(',').try(:first)
end
data = {
v: 1,
tid: ENV['GA_TRACKING_CODE'],
t: 'pageview',
dl: dl,
uid: uid,
aid: aid,
an: an,
cid: cid,
uip: request.remote_ip,
aip: 1,
ua: request.user_agent,
ul: ul,
cg1: cg1,
plt: srt,
srt: srt, #ignored by google
dt: cg1,
cm: 'api',
cs: an,
ci: "oauth_app.#{aid}"
}
url = URI('https://www.google-analytics.com/collect?'+data.to_query)
# dont wait around for this
Thread.start do
begin
res = Net::HTTP.get_response(url)
logger.info "#{url} => #{res.inspect}"
rescue StandardError => err
logger.error "#{url} #{err}"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment