Sheharyar Naseer

Using Google Analytics in Rails 4 with Turbolinks


There doesn’t seem to be a proper way of using Google Analytics in a Rails 4 app when Turbolinks are involved. So I’m just writing here what works for me. I’ve written this for the new Google Universal Analytics, and this guide uses the Slim Templating Language but you can just as easily use it with erb or haml.

Create a _google_analytics.html.slim file in your app/views/layouts folder, and paste in the script you got from the Google Analytics website as is:

- if Rails.env.production?
    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','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-XXXXXXXX-X', 'auto');
        ga('send', 'pageview');

Now, create a google_analytics.coffee file in your app/assets/javascripts directory, and paste in this:

jQuery ->
  $(document).on 'page:change', ->
    if window.ga?
      ga('set',  'location', location.href.split('#')[0])
      ga('send', 'pageview', { "title": document.title })

This file will track the page again, whenever turbolinks loads a new page. In your application.html.slim, render the layout right before closing the head tag:

doctype html
html
  head
    title My Rails App

    / Some code...

    == stylesheet_link_tag 'application', params[:controller], media: 'all'
    == render 'layouts/google_analytics'

  body
    / Some more code...

Finally, in your application.js, require the coffee file we previously created:

//= require jquery
//= require jquery_ujs
//= require google_analytics

var someJavascriptStuff = {};

Now, you’re good to go.