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?
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

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

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

jQuery ->
  $(document).on 'page:change', ->
      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
    title My Rails App

    / Some code...

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

    / 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.