Google Analytics in your Rails application using javascript_include_tag

by Mike Zazaian at 2009-08-06 04:15:23 UTC in rails

A DRY, syntactically elegant way to track the traffic of your Rails application with Google Analytics

5 comments no links

Here's a (mostly) idiot-proof way to include Google Analytics tracking code in your Rails (or other Ruby-based framework) application.

First, I created a footer partial in /app/views/all/_footer.haml (yes, I use mostly HAML, except for in long forms -- the syntax is truly poetic), with the following lines at the top:

#!/app/views/all/_footer.haml

= javascript_include_tag "analytics/one"
= javascript_include_tag "analytics/two"

Easy enough. If you reload your app at this point, surprise surprise, you'll get an error message, because there's nothing at either of the javascript_include_tag locations. It's okay, we'll fix that now.

First create a directory called 'analytics' in '/public/javascripts/'. This saves us the hassle of having to use names like analytics_one.js and analytics_two.js, which is ugly, and redundant, and clutters up our delightful public/javascripts directory which we'll likely want to populate with all kinds of goodies later. But anyway...

Now we have to create the two javascript files, each with its respective half of the analytics code. Why two? As you'll notice, Google has included our plug-and-play analytics code inside of two separate script tags. The first being the Analytics javascript library that Google provides, and the second being the trigger for said library. While we might get away with combining them into one file on some systems, it's best practice to keep them separated into two.

That said, let's create the first:

#!/public/javascripts/analytics/one.js

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

Cool, there's the library. If you've created your analytics account recently (around the publish date of this article), you should be able to plug this code directly into your own file, and you'll be good to go. This is not so with the second file:

#!/public/javascripts/analytics/two.js

try {
  var pageTracker = _gat._getTracker("UA-XXXXXXXX-X");
  pageTracker._trackPageview();
} catch(err) {}

This gentleman should look primarily the same, but you will, of course, have to replace the series of nine X's "UA-XXXXXXXX-X" with your own Analytics id code that Google provides (note the hyphen before the last digit).

Good. With that out of the way, we've got our two wonderful bits of analytics javascript, and even a delightful little footer to call them so that we don't have to paste them into every single view or layout that we have, and can edit them more easily if for whatever reason we need to. Certainly very DRY.

NOW, because we've got our _footer.haml partial, all we need to do is render this at the very bottom of whatever layouts we may have employed at /app/views/layouts. If you don't have any layouts at this point, tisk-tisk. You really should. And if your application is small enough as not to warrant the use of layouts, you should be using Sinatra.

Anyway -- layouts. They're good. For the sake of argument, we'll pretend you have a layout, and that it looks something like this:

#!/app/views/layouts/application.haml

!!!
%html
  -# <head> code goes here </head>
  %body
    #content
      #primary
        = yield
      #secondary
        = render :partial => "some_partial"
        = render :partial => "another_partial"
    = render :partial => "/all/footer"

See that last render :partial => call? That's our footer. Yeah, I jumped the gun a little bit. We call it with "/all/footer" rather than just "footer" because it's in our views/all directory.

Remember, if you have additional layouts, for, say your articles controller, or users controller, you'll have to render the footer partial in the same way on those in order for their pages to be tracked accordingly.

It's also important to note (for HAML users, anyway), that the footer partial is four spaces from the left margin, making it even with the #content div and one level below the %body tag. This is because, as Google recapitulates many, many times, their code should ideally be the last thing included before the tag at the end of the page.

If you're using erb, or Markaby, or Parkaby, or some other templating system, you obviously don't need to observe the spacing, but just be sure to call render :partial => "/all/footer" just before that body close tag.

By that same token, it's worth noting that if you re-use that footer partial, be sure to put any new code above the javascript_include_tag calls, ensuring that the Analytics code is kept at the bottom of the file, just inside the body tag.

And that's it! Don't worry if Analytics doesn't start tracking your stats right away -- it takes a seemingly arbitrary number of hours (somewhere between 2 and 20) to acknowledge that your code is in place and is indeed working. To check this, just go to the overview page in your Analytics account and click on the site account that you're trying to track. You'll see a green check mark in the status column here if the code is working and Analytics is actively tracking your site traffic, a clock icon if your tracker has been acknowledged but Analytics is in the process of aggregating your site data, or a yellow caution sign with an exclamation mark if Analytics has attempted to track your site but can't.

This last one, the caution sign, is the only one that you'll have to do anything about. Just go back over your code, check it against what I've got above here in the tutorial, and make sure you dotted your equals signs and crossed your percentages. If you're still having trouble, either contact a member of the staff of post your issue as a comment and we'll be happy to help you out.

And that's it -- clean, easy Analytics include tags without cluttering your source code with all that nasty javascript. Does life get any better? Well, yes, but it's still nice to take pleasure in the little things...

5 comments

Re at 2010-01-24 22:37:40 UTC

I guess that everybody must keep in memory if see the the best custom writing corporation, that will be a chance to get the useful thing about this good post or purchase the a custom essay corresponding with make an order. Moreover, this is good choice. Try it here!

Re at 2010-02-04 05:25:54 UTC

To perform the thesis topic referring to this post wasn’t effortless though you cope with that. If every single writer is as good as you are, all students would never have got problems with the dissertation writing service.

Re at 2010-02-05 18:14:01 UTC

Custom thesis or dissertation writing would be acceptable for all people. And you write best define dissertation just about this good topic.

Re at 2010-02-08 20:52:04 UTC

It's not so simple to make a professional written essay, especially if you are engaged. I advise you to define buy an essay and to be devoid from distrust that your work will be done by essays writers

benny at 2010-02-18 19:12:46 UTC

The first being the Analytics javascript library that Google provides, and the second being the trigger for said library. Library App

post comment
Comments are marked down using Ryan Tomayko's excellent rdiscount gem, which follows standard markdown conventions. If you don't know markdown, you can learn it using the Daring Fireball markdown syntax guide.
required
required
login to post comments without entering your name, email address and recaptcha code each time, or register if you haven't already done so

markdown basics

**bold** __bold__ [link](http://link.com "link") * unordered list item
*italic* _italic_ ##h2 heading 1. ordered list item
> blockquote ####h4 heading <code>@ruby</code>

latest links

ActiveScaffold A Ruby on Rails plugin for dynamic, AJAX CRUD interfaces
rsl's stringex at master - GitHub Some [hopefully] useful extensions to Ruby’s String class. It is made up of three libraries: ActsAsUrl [permalink solution with better character translation], Unidecoder [Unicode to Ascii transliteration], and StringExtensions [miscellaneous helper methods for the String class].
friendly-id's friendly_id-2.1.4 Documentation

login

register activate reset

feeds

articles/rss

topics

staff

editor

about

doblock focuses on ruby, rails, and all things that can help ruby and/or rails programmers hone their skills.

Techniques, tutorials, news, and even free open-source applications, doblock seeks to fill in the cracks of the ruby/rails blogosphere.

doblock v. 0.8.22 powered by Rails