Blog posts for Ruby, Ruby on rails and Linux.

Go back to all blogs

google analytics for rails 4 and turbolinks

Kapil Raj Nakhwa2013-Nov-11
Now we all know that google analytics is a great tool to gather key insight into our site and monitor our visitor behaviours which help in further planning and targeting of our site to achieve the key goals.
Installing google analytics also used to be an easy task in rails 3 with simple snippet adding into each of our html pages.All we had to do was to put the snippet provided by the google analytics tracking snipplet into our code.
We just needed to visit the Google analytics page and obtain our tracking ID. Now like I said before we needed to put the google analytics tracking snippet into each of our pages which needed to be tracked and in rails the easiest method was to add a partial in the footer of the layout file.
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

  ga('create', 'UA-XXXXXXX-XX', '');
  ga('send', 'pageview');

Where UA-XXXXXXX-XX represents the tracking code you received. We could include this in all the pages by including this above partial in the layout file.
Say we are using the
application.html.erb layout in our application then we can include the above partial by adding <%= render "shared/footer"%> in the bottom of the layout file.

This would work in flawlessly in most of the rails 3 application but however since rails 4 and arrival of turbolinks which rails 4 uses by default this would not work. Since in rails 4 using turbolinks just updates the body and the title of the page while technically the page remains the same the google tracking code is not updated and hence it behaves as it is in still in the same page.

To work around this problem  either we can remove turbolinks from our application by removing it from the Gemfile and removing it's reference from the application.js manifest file or we can use the following work around.
Make a seperate js file like below.
$(document).on 'page:change', ->
  if window._gaq?
    _gaq.push ['_trackPageview']
  else if window.pageTracker?

This script than can be included in the application.js manifest file by adding the following line to it
//= require analytics . What this does is it asks google analytics to trigger on each page change event instead of page load so that each change with the turbolink is noticed by the google analytics tracker. And we can reap the benefit that google analytics brings to our lives.


Tags: Rails-4,Turbolinks,google analytics

Go back to all blogs
Never miss a post on new ruby and rails tips