-
Notifications
You must be signed in to change notification settings - Fork 3
rails google analytics
Last updated 18 December 2013
Website analytics for Rails applications. 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’re new to Rails, see What is Ruby on Rails?, the book Learn Ruby on Rails, and recommendations for a Rails tutorial.
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.” Each application is accompanied by a tutorial so there is no mystery code. Support for the project comes from subscribers. Please accept our invitation to join the RailsApps project.
Analytics services provide reports about website traffic and usage.
You’ll use the data to increase visits and improve your site. Analytics close the communication loop with your users; your website puts out a message and analytics reports show how visitors respond.
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.
A conventional installation of Google Analytics requires adding JavaScript to every page of the Rails application. This can be accomplished by modfiying the application layout and adding additional JavaScript as an application asset.
First let’s look at 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.
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.
There are five approaches to adding the Google Analytics tracking code to a Rails 3.2 application:
- add the Google tracking code to the application layout
- add a partial included in the application layout
- use view helpers such as Benoit Garret’s google-analytics-rails gem
- use Rack middleware such as Lee Hambley’s rack-google-analytics gem
- add the Google tracking code to the asset pipeline
All these approaches work for Rails 3.2. It doesn’t matter to Google how the script gets injected.
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.
Rails 4.0 introduced a feature named Turbolinks to increase the perceived speed of a website.
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.
Viist the Google Analytics website to obtain a Tracking ID for your website. You’ll need to know the domain name of your website before you set up a Google Analytics account for your website.
Heroku is a popular hosting platform for Rails applications. If you’ve deployed to Heroku without a custom domain, your domain name will look like “myapp.herokuapp.com”. When you set up your account, use it for fields for “Website Name,” “Web Site URL,” and “Account Name.”
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 it is provided below. But take a minute to compare the code that Google provides to make sure it hasn’t changed from what’s provided here.
You’ll check your Google Analytics account later to verify that Google is collecting data.
The Google Analytics JavaScript library must be included on every page.
Ordinarily, JavaScript for every page goes in the app/assets/javascripts/application.js file. To resolve the Turbolinks problem, we want the Google Analytics JavaScript snippet to load after Turbolinks, so we’ll add it to the default application layout with a partial template.
A partial is similar to any view file, except the filename begins with an underscore character. We’ll save the file in a view folder and use the render
keyword to insert the partial in the default application layout.
Create a file app/views/layouts/_footer.html.erb:
<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-XXXXXXX-XX', 'herokuapp.com'); ga('send', 'pageview'); </script>
This code should be identical to the tracking code snippet you were offered when you created your Google Analytics account (but check it to be sure).
You must replace UA-XXXXXXX-XX
with your tracking ID.
This example was created for a website hosted on Heroku. The tracking code specifies the herokuapp.com domain but can be used on any herokuapp.com subdomain such as myapp.herokuapp.com. Change the domain if you are using a custom domain.
You may have one or more application layout files. You must add the partial to each application layout if you want to track all pages.
The default application layout is the file app/views/layouts/application.html.erb.
Add the partial to an application layout by including:
<%= render 'layouts/footer' %>
Note the underscore and file extension are dropped from the filename _footer.html.erb.
Here is a typical default application layout found in the file app/views/layouts/application.html.erb. This application layout is set up to use Twitter Bootstrap and includes a footer partial.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><%= content_for?(:title) ? yield(:title) : "Learn Rails" %></title> <meta name="description" content="<%= content_for?(:description) ? yield(:description) : "Learn Rails" %>"> <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %> <%= javascript_include_tag "application", "data-turbolinks-track" => true %> <%= csrf_meta_tags %> </head> <body> <header> <%= render 'layouts/navigation' %> </header> <main role="main"> <%= render 'layouts/messages' %> <%= yield %> </main> <footer> <%= render 'layouts/footer' %> </footer> </body> </html>
You can learn more about the default application layout in an article about the Rails Default Application Layout.
With the footer partial in place, the Google Analytics JavaScript library will be added on every page.
Ordinarily, that’s all you need to send tracking data to Google Analytics. But we have to add a Turbolinks workaround for Rails 4.0 or newer versions.
With Turbolinks, the Google Analytics JavaScript library is not sufficient to record a page visit for every page update. We’ll add a Turbolinks workaround.
The workaround should be loaded on every page and it can be included as an application-wide asset (it will load before Turbolinks).
Add the file app/assets/javascripts/analytics.js.coffee to include the Turbolinks workaround:
$(document).on 'page:change', -> if window._gaq? _gaq.push ['_trackPageview'] else if window.pageTracker? pageTracker._trackPageview()
The manifest directive //= require_tree .
in the file app/assets/javascripts/application.js insures that the Turbolinks workaround 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.
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 page has been parsed and changed to the new version by Turbolinks. The code listens for the page:change
event and calls either of two Google Analytics JavaScript methods that send data to Google Analytics.
This version of the workaround was initially suggested by Shuky Dvir on Nick Reed’s site Turbolinks Compatibility.
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 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.
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.
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 all the methods in analytics.js that we want to stub. window.analytics.methods = ['identify', 'track', 'trackLink', 'trackForm', 'trackClick', 'trackSubmit', 'page', 'pageview', 'ab', 'alias', 'ready', 'group', 'on', 'once', 'off']; // Define a factory to create queue stubs. These are placeholders for the // "real" methods in analytics.js so that you never have to wait for the library // to load asynchronously to actually track things. The `method` is always the // first argument, so we know which method to replay the call into. 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 method. for (var i = 0; i < window.analytics.methods.length; i++) { var method = window.analytics.methods[i]; window.analytics[method] = window.analytics.factory(method); } // Define a method that will asynchronously load analytics.js from our CDN. window.analytics.load = function (apiKey) { // Create an async script element for analytics.js based on your API key. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = ('https:' === document.location.protocol ? 'https://' : 'http://') + 'd2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/' + apiKey + '/analytics.min.js'; // Find the first script element on the page and insert our script next to it. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }; // Add a version so we can keep track of what's out there in the wild. window.analytics.SNIPPET_VERSION = '2.0.6'; // Load analytics.js with your API key, which will automatically load all of the // analytics integrations you've turned on for your account. Boosh! window.analytics.load('YOUR_API_TOKEN'); // Make our first page call to load the integrations. If you'd like to manually // name or tag the page, edit or move this call to use your own tags. 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 your “Settings” page when you log in to Segment.io (it is labelled “Your API 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.
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).
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.
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.
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.
Daniel Kehoe wrote 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.