Installing Google Analytics into a Ruby on Rails 3.X

Installing Google Analytics into a Ruby on Rails app is pretty straight forward, however, the key is to only execute the analytics script in PRODUCTION environment. Without doing this, you’ll end up counting page views and visits on all your environments, e.g. development and test.

Step – 1

Go to Google Analytics to create an account and get the tracking script. After creating an account, Google Analytics will provide a javascript that you’ll need to copy into your rails app. The javascript looks something like this:

<script type=”text/javascript”>
var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.&#8221; : “http://www.&#8221;);
document.write(unescape(“%3Cscript src='” + gaJsHost + “’ type=’text/javascript’%3E%3C/script%3E”));
<script type=”text/javascript”>
try {
var pageTracker = _gat._getTracker(“UA-XXXXXXX-X”);
} catch(err) {}</script>

Step – 2

Create a partial in your app/views/layouts directory and paste the Google Analytics javascript code into the partial. I named my partial _ga.html.erb

Step – 3

Call the above partial in your application.html.erb. Righ at the bottom of application.html.erb (before </body>, render the partial.
<%= render :partial => ‘layouts/ga’ if Rails.env == ‘production’ %>

The key here is to only call google analytics if you are in a production environment! If you don’t, you’ll see test data from development or test environments corrupting your analytics results!

that’s it!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s