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 + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));
</script>
<script type=”text/javascript”>
try {
var pageTracker = _gat._getTracker(“UA-XXXXXXX-X”);
pageTracker._trackPageview();
} 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!

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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