Skip to content

Instantly share code, notes, and snippets.

@priom
Forked from the-bass/application.html.erb
Created March 24, 2017 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save priom/6025b1e56a39daeaa9a2464ca651ad54 to your computer and use it in GitHub Desktop.
Save priom/6025b1e56a39daeaa9a2464ca651ad54 to your computer and use it in GitHub Desktop.
Using Google Analytics with Rails 5 and Turbolinks 5. This code is taken from the conversation between @preetpalS and @packagethief on https://github.com/turbolinks/turbolinks/issues/73.
<%# Put this code snippet between the <head></head>-tags in your application layout and %>
<%# replace 'UA-XXXXXXXX-X' with your own unique Google Analytics Tracking ID %>
<%# ... %>
<head>
<%# ... %>
<% if Rails.env.production? %>
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'auto');
</script>
<% end %>
</head>
<%# ... %>
# Put this file into your assets/javascripts/ folder and assure
# it gets loaded by checking or editing your assets/javascripts/application.js
# file as appropriate
document.addEventListener 'turbolinks:load', (event) ->
if typeof ga is 'function'
ga('set', 'location', event.data.url)
ga('send', 'pageview')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment