read

Here's a very simple way of getting Google Universal Analytics tracking code to work with Rails 4 using Turbolinks, without using any tricky 3rd party Javascript code.

Partials

If you don't have one already, go ahead and create a "partials" folder within your views folder. This will contain partial files to keep your main views clean and allow you to easily reuse the code when needed.

Google Universal Analytics

Inside the partials folder, create a file named _google_analytics.html.erb with the following content:

<script>
(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');
</script>

This is your default Universal Analytics code with only one change: the ga('send', 'pageview') line was deleted.
The file will be included in the <head> section of your website, but we'll cover that later.

Pageview tracking

Create a file named _google_analytics_pageview.html.erb inside the partials folder, with the following content:

<script>
    ga('send', 'pageview', '<%= request.path %>');
</script>

This file will make sure each pageview is tracked correctly when Turbolinks replaces the <body> content of your page.

Gluing things together

In your master layout (usually /views/layouts/application.html.erb), include the following line inside the <head> section:

<%= render partial: "partials/google_analytics" %>

On the line before the <\body> tag, include this line:

<%= render partial: "partials/google_analytics_pageview" %>

You're done! Your pageviews are now being tracked by Google Analytics.

How does it work?

Rails Turbolinks will replace only the <body> content of your website when you change pages.

By separating the Analytics code into different files, we can leverage Turbolinks to request the Universal Analytics code only once, by placing it within the <head> section, and then tracking pageviews with a single line of Javascript that's within the <body> section and thus replaced (and therefore called) by Turbolinks when the page changes.

Because of the nature of Turbolinks, the auto URI detection breaks, and we need to explicitily pass it to the pageview tracking method. Fortunately this is really easy to accomplish with the request.path Rails helper.

Blog Logo

Rui Gomes

Web Developer, Internet Marketing enthusiast and Student@FEUP. That pretty much sums it up.


Published

Image

Rui Gomes

Knowledge share with a great deal of random thoughts.

Back to Overview