Tuesday, 3 September 2013

How to Implement Google Analytics in your Application within a short span of time

Installing Google Analytics in a Ruby on Rails App is Pretty cool and easy. However it is only to execute the analytics script in Production environment. Without doing this, you’ll end up counting page views and visits on all your environments.

 So Let me describe the Process Step wise so that it will be more easier for you to implement in your app.

Step1
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>
Step2
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.

Step3
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’ %>

 And here it is !!!

You have now installed Google Analytics successfully on your app. Remember... You must have to run your app on Production mode to get it installed.

Is not it so easy/?   :)
Post a Comment