becos life is about pushing the envelope playfully

rails


Google Analytics and Rails in 3 Steps and Less Than 5 minutes

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.” : “http://www.”);
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!

And that’s it! Super easy to get Google Analytics running in your Ruby on Rails app in less than 5 minutes!

10:32 am, by aihui
permalink
tagged: tech, rails,


   Comments