Analytics for Rails

by Daniel Kehoe

Last updated 20 July 2014

Website analytics for Ruby on Rails applications, including Google Analytics and alternatives. How to install Google Analytics with Rails Turbolinks. Event tracking and more with Segment.io, Mixpanel, KISSmetrics and others.

If You Are New to Rails

If you’re new to Rails, see What is Ruby on Rails?, the book Learn Ruby on Rails, and recommendations for a Rails tutorial.

Join RailsApps

What is the RailsApps Project?

This is an article from the RailsApps project. The RailsApps project provides example applications that developers use as starter apps. Hundreds of developers use the apps, report problems as they arise, and propose solutions. Rails changes frequently; each application is known to work and serves as your personal “reference implementation.” Support for the project comes from subscribers. If this article is useful to you, please accept our invitation to join the RailsApps project.

Introduction

Analyze your website traffic and usage with analytics services. Analytics close the communication loop with your users; your website puts out a message and analytics reports show how visitors respond. You can use the data to increase visits and improve your site.

Google Analytics is the best known tracking service. It is free, easy to use, and familiar to most web developers. In this article you’ll learn how to add Google Analytics to a Rails application, specifically addressing a known problem with the Rails Turbolinks feature.

We’ll look at two ways to install Google Analytics for Rails 4.0 and newer versions. First we’ll look at a conventional approach and see how Google Analytics works. Then I’ll show an alternative approach using the Segment.io service. The service provides an API to send analytics data to dozens of different services, including Google Analytics.

Rails Composer

The RailsApps project provides a tool, Rails Composer, to generate Rails starter applications. You get a choice of front-end frameworks, template engines, authentication, authorization, and many other options to create a complete application almost instantly.

Rails Composer gives you a choice of analytics, either Google Analytics or Segment.io, when you generate a starter application. If you don’t have time to read this article, just run Rails Composer.

Google Analytics

A conventional installation of Google Analytics requires adding JavaScript to every page of the Rails application. This can be accomplished by adding additional JavaScript as an application asset.

First let’s look at how Google Analytics works.

How Google Analytics Works

To collect usage and traffic data, every web page must contain a snippet of JavaScript code, referred to as the Google Analytics Tracking Code. The tracking code snippet includes a unique website identifier named the Google Analytics Tracking ID, which looks like this: UA-XXXXXXX-XX. You will obtain the JavaScript snippet and Tracking ID from the Google Analytics website when you set up an account for your website.

The tracking code snippet loads a larger JavaScript library (a 20KB file named analytics.js) from the Google webserver that serves as a web beacon. The analytics.js file is downloaded once and cached for the remainder of the session; often, it is already cached and doesn’t need to be downloaded because a visitor has (very likely) visited another website that cached the file.

Before December 2009, Google’s JavaScript code could slow the loading of a page because page rendering could be blocked until the Google code finished downloading. Google introduced asynchronous JavaScript code to improve page performance. Now, the analytics.js file downloads in parallel with other page assets. Page rendering can begin before the analytics.js file is delivered. In practice, the analytics.js file is often already cached.

Google recommended placing the original (synchronous JavaScript) snippet immediately before the final </body> close tag because it could delay page loading. Now, Google recommends placing the new (asynchronous JavaScript) snippet immediately before the closing </head> tag because it has little effect on page loading. This is ideal because the asynchronous JavaScript snippet can be included in your Rails project’s app/assets/javascripts/ folder, where it can be managed by the Rails asset pipeline.

Each time the browser displays a new page, the JavaScript code sends data to the Google Analytics service. The data includes the URL of the requested page, the referring (previous) page, and information about the visitor’s browser, language, and location.

Older Approaches

For Rails 3.2, there were four approaches for adding the Google Analytics tracking code. You may see these approaches described in older articles:

  1. add the Google tracking code to the application layout
  2. add a partial included in the application layout
  3. use view helpers such as Benoit Garret’s google-analytics-rails gem
  4. use Rack middleware such as Lee Hambley’s rack-google-analytics gem

These approaches are no longer relevant for Rails 4.0 and newer versions.

Google Analytics for Rails 4.2

Rails 4.0 introduced a feature named Turbolinks to increase the perceived speed of a website.

Google Analytics doesn’t work for a Rails 4.0 or newer web applications. To be more precise, it won’t work for all pages. It can be made to work with a workaround to accommodate Turbolinks.

Turbolinks makes an application appear faster by only updating the body and the title of a page when a link is followed. By not reloading the full page, Turbolinks reduces browser rendering time and trips to the server. With Turbolinks, the user follows a link and sees a new page but Google Analytics thinks the page hasn’t changed because a new page has not been loaded.

You can disable Turbolinks by removing the turbolinks gem from the Gemfile and removing the reference in the app/assets/javascripts/application.js file. However, it’s nice to have both the speed of Turbolinks and Google Analytics tracking data. This article details a workaround for the Turbolinks problem.

Google Analytics Account

Visit the Google Analytics website to obtain a Tracking ID for your website. Accept the defaults when you create your Google Analytics account and click “Get Tracking ID.” Your tracking ID will look like this: UA-XXXXXXX-XX. You won’t need the tracking code snippet as we provide an alternative here.

Google Analytics Tracking Script

Instead of using the tracking code snippet provided by Google, I recommend using an alternative created by Jonathon Wolfe and provided on Nick Reed’s Turbolinks Compatibility site.

Create a file app/assets/javascripts/google_analytics.js.coffee:

class @GoogleAnalytics

  @load: ->
    # Google Analytics depends on a global _gaq array. window is the global scope.
    window._gaq = []
    window._gaq.push ["_setAccount", GoogleAnalytics.analyticsId()]

    # Create a script element and insert it in the DOM
    ga = document.createElement("script")
    ga.type = "text/javascript"
    ga.async = true
    ga.src = ((if "https:" is document.location.protocol then "https://ssl" else "http://www")) + ".google-analytics.com/ga.js"
    firstScript = document.getElementsByTagName("script")[0]
    firstScript.parentNode.insertBefore ga, firstScript

    # If Turbolinks is supported, set up a callback to track pageviews on page:change.
    # If it isn't supported, just track the pageview now.
    if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
      document.addEventListener "page:change", (->
        GoogleAnalytics.trackPageview()
      ), true
    else
      GoogleAnalytics.trackPageview()

  @trackPageview: (url) ->
    unless GoogleAnalytics.isLocalRequest()
      if url
        window._gaq.push ["_trackPageview", url]
      else
        window._gaq.push ["_trackPageview"]
      window._gaq.push ["_trackPageLoadTime"]

  @isLocalRequest: ->
    GoogleAnalytics.documentDomainIncludes "local"

  @documentDomainIncludes: (str) ->
    document.domain.indexOf(str) isnt -1

  @analyticsId: ->
    # your google analytics ID(s) here...
    'UA-XXXXXXX-XX'

GoogleAnalytics.load()

You must replace UA-XXXXXXX-XX with your Google Analytics tracking ID.

The file contains CoffeeScript, a programming language that adds brevity and readability to JavaScript. Turbolinks fires events to provide hooks into the lifecycle of the page. The page:change event fires when a new page is loaded in the browser, or when a page has been parsed and changed to the new version by Turbolinks. The code listens for the page:change event and calls a Google Analytics JavaScript method that sends data to Google Analytics.

The manifest directive //= require_tree . in the file app/assets/javascripts/application.js insures that the tracking code is included in the concatenated application JavaScript file. If you’ve removed the //= require_tree . directive, you’ll have to add a directive to include the Turbolinks workaround file.

With this approach, there is no need to modify the application layout file. The script provides Google Analytics tracking whether or not TurboLinks is enabled.

The script contains a @isLocalRequest: method which won’t send data to Google if the URL domain includes local. This prevents pageview tracking when you use http://localhost:3000/ in development. You can also provide multiple Google Analytics IDs in the @analyticsId: method.

Deploy

If you wish to deploy to Heroku, you must recompile assets and commit to the Git repo:

$ git add -A
$ git commit -m "analytics"
$ RAILS_ENV=production rake assets:precompile
$ git add -A
$ git commit -m "assets compiled for Heroku"

Then you can deploy to Heroku:

$ git push heroku master

See the article Rails and Heroku for more on deploying to Heroku. For Rails 4.0 and newer versions, your Gemfile must include the rails_12factor gem to serve assets from the Rails asset pipeline; our analytics JavaScript won’t work without the gem.

Log into your Google Analytics account to see real-time tracking of visits to your website. Under “Standard Reports” see “Real-Time Overview.” You’ll see data within seconds after visiting any page.

Segment.io

Segment.io is a subscription service that gathers analytics data from your application and sends it to dozens of different services, including Google Analytics. The service is free for low- and medium- volume websites, providing 100,000 API calls (page views or events) per month at no cost. There is no charge to sign up for the service.

Using Segment.io means you install one JavaScript library and get access to reports from dozens of analytics services. You can see a list of supported services. The company offers helpful advice about which analytics tools to choose from. For low-volume sites, many of the analytics services are free, so Segment.io makes it easy to experiment and learn about the available analytics tools. The service is fast and reliable, so there’s no downside to trying it.

If you’ve followed instructions above and installed Google Analytics using the conventional approach, be sure to remove the code before installing Segment.io.

Accounts You Will Need

You will need an account with Segment.io. Sign up for Segment.io.

You will need accounts with each of the services that you’ll use via Segment.io.

You’ll likely want to start with Google Analytics, so get a Google Analytics account and tracking ID as described in the section Google Analytics Account above.

Installing the JavaScript Library

Segment.io provides a JavaScript snippet that sets an API token to identify your account and installs a library named analytics.js. This is similar to how Google Analytics works. Like Google Analytics, the Segment.io library loads asynchronously, so it won’t affect page load speed.

The Segment.io JavaScript snippet should be loaded on every page and it can be included as an application-wide asset using the Rails asset pipeline.

Add the file app/assets/javascripts/segmentio.js to include the Segment.io JavaScript snippet:

  // Create a queue, but don't obliterate an existing one!
  window.analytics = window.analytics || [];

  // A list of the methods in Analytics.js to stub.
  window.analytics.methods = ['identify', 'group', 'track',
    'page', 'pageview', 'alias', 'ready', 'on', 'once', 'off',
    'trackLink', 'trackForm', 'trackClick', 'trackSubmit'];

  // Define a factory to create stubs. These are placeholders
  // for methods in Analytics.js so that you never have to wait
  // for it to load to actually record data. The `method` is
  // stored as the first argument, so we can replay the data.
  window.analytics.factory = function(method){
    return function(){
      var args = Array.prototype.slice.call(arguments);
      args.unshift(method);
      window.analytics.push(args);
      return window.analytics;
    };
  };

  // For each of our methods, generate a queueing stub.
  for (var i = 0; i < window.analytics.methods.length; i++) {
    var key = window.analytics.methods[i];
    window.analytics[key] = window.analytics.factory(key);
  }

  // Define a method to load Analytics.js from our CDN,
  // and that will be sure to only ever load it once.
  window.analytics.load = function(key){
    if (document.getElementById('analytics-js')) return;

    // Create an async script element based on your key.
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.id = 'analytics-js';
    script.async = true;
    script.src = ('https:' === document.location.protocol
      ? 'https://' : 'http://')
      + 'cdn.segment.io/analytics.js/v1/'
      + key + '/analytics.min.js';

    // Insert our script next to the first script element.
    var first = document.getElementsByTagName('script')[0];
    first.parentNode.insertBefore(script, first);
  };

  // Add a version to keep track of what's in the wild.
  window.analytics.SNIPPET_VERSION = '2.0.9';

  // Load Analytics.js with your key, which will automatically
  // load the tools you've enabled for your account. Boosh!
  window.analytics.load('YOUR_API_TOKEN');

  // Make the first page call to load the integrations. If
  // you'd like to manually name or tag the page, edit or
  // move this call however you'd like.
  /*  */
  window.analytics.page();

If you previously installed the file app/assets/javascripts/analytics.js.coffee in the Google Analytics instructions above, be sure to remove it. Also remove the footer file and partial from the default application layout if you haven’t already.

The Segment.io website offers a minified version of the snippet for faster page loads. You can use it if you wish; the non-minified version is provided above so you can read the code and comments.

You must replace YOUR_API_TOKEN with your Segment.io API token. You can find the API token on under “Project Settings” under the “API Keys” tab when you log in to Segment.io (it is labelled “Write Key”).

The manifest directive //= require_tree . in the file app/assets/javascripts/application.js insures that the Segment.io JavaScript snippet is included in the concatenated application JavaScript file. If you’ve removed the //= require_tree . directive, you’ll have to add a directive to include the app/assets/javascripts/segmentio.js file.

Page View Tracking with Turbolinks

To make sure every page is tracked when Rails Turbolinks is used, append the following JavaScript to the app/assets/javascripts/segmentio.js file:

// accommodate Turbolinks and track page views
$(document).on('ready page:change', function() {
  analytics.page();
})

Add this code at the end of the file.

Turbolinks fires a page:change event when a page has been replaced. The code listens for the page:change event and calls the Segment.io analytics.page() method. This code will work even on pages that are not visited through Turbolinks (for example, the first page visited).

Event Tracking

Segment.io gives us a convenient method to track page views. Page view tracking gives us data about our website traffic, showing visits to the site and information about our visitors.

It’s also important to learn about a visitor’s activity on the site. Site usage data helps us improve the site and determine whether we are meeting our business goals. This requires tracking events as well as page views.

The Segment.io JavaScript library gives us two methods to track events:

  • trackLink
  • trackForm

Link tracking can be used to send data to Segment.io whenever a visitor clicks a link. It can be useful if you add links to external sites and want to track click-throughs. The method can also be used to track clicks that don’t result in a new page view, such as changing elements on a page.

The trackForm method is very useful for event tracking as many of the significant events on a website are the result of form submissions. Append it to the app/assets/javascripts/segmentio.js file:

// accommodate Turbolinks
// track page views and form submissions
$(document).on('ready page:change', function() {
  console.log('page loaded');
  analytics.page();
  analytics.trackForm($('#new_visitor'), 'Signed Up');
  analytics.trackForm($('#new_contact'), 'Contact Request');
})

I’ve included a console.log('page loaded') statement so you can check the browser JavaScript console to see if the code runs as expected.

The trackForm method takes two parameters, the ID attribute of a form and a name given to the event. Here we assume we have a form with the ID attribute “new_visitor” and we want to identify the event as “Signed Up.”

With Google Analytics enabled as a Segment.io integration, you’ll see form submissions appear in the Google Analytics Real-Time report, under the “Events” heading.

You can read more about the Segment.io JavaScript library in the Segment.io documentation.

Segment.io Integrations

After installing the Segment.io JavaScript snippet in your application, visit the Segment.io integrations page to select the services that will receive your data. When you log in to Segment.io you will see a link to “Integrations” in the navigation bar.

Each service requires a different configuration information. At a minimum, you’ll have to provide an account identifier or API key that you obtained when you signed up for the service.

For Google Analytics, enter your Google Analytics tracking id. It looks like UA-XXXXXXX-XX.

Click “Dashboard” in the navigation bar so you can monitor data sent to Segment.io from your application.

When you test the application locally, you should see the results of page visits and form submissions within seconds in the Segment.io Dashboard.

With Google Analytics enabled as a Segment.io integration, you’ll see form submissions appear in the Google Analytics Real-Time report, under the “Events” heading.

Note that Google doesn’t process their data in real-time in most of its reports. Data only appears immediately in the Google Analytics Real-Time report. Other Google Analytics reports, such as the Audience report, won’t show data immediately. Check the next day for updated reports.

Deploy

If you wish to deploy to Heroku, you must recompile assets and commit to the Git repo:

$ git add -A
$ git commit -m "analytics"
$ RAILS_ENV=production rake assets:precompile
$ git add -A
$ git commit -m "assets compiled for Heroku"

Then you can deploy to Heroku:

$ git push heroku master

See the article Rails and Heroku for more on deploying to Heroku. For Rails 4.0 and newer versions, your Gemfile must include the rails_12factor gem to serve assets from the Rails asset pipeline; our analytics JavaScript won’t work without the gem.

You should see real-time tracking of data sent to Segment.io in the Segment.io dashboard.

Log into your Google Analytics account to see real-time tracking of visits to your website. Under “Standard Reports” see “Real-Time Overview.” You’ll see data within seconds after visiting any page.

Credits

Daniel Kehoe wrote the article.

Did You Like the Article?

Was this useful to you? Follow @rails_apps on Twitter and tweet some praise. I’d love to know you were helped out by the article.

Any issues? Please leave a comment below.

Comments

Is this helpful? Your encouragement fuels the project. Please tweet or add a comment. Couldn't get something to work? For the example apps and tutorials, it's best to open an issue on GitHub so we can help you.

comments powered by Disqus