How to Integrate Google Analytics in Rails 3 Application?


Google Analytics is a great tool to present statistics on your websites performance. 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 will end up counting page views and visits on all your environments, e.g. development and test.

Google Analytics in Rails 3 in Three Simple Steps:

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 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.jstype=’text/javascript3E%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 (I named my partial _ga.html.erb) in your app/views/layouts directory and paste the Google Analytics JavaScript code into the partial. This code talks to Google Analytics every time someone visits the page, and that’s how it all works.

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

But if you don’t want to track all pages of your application then you can render the Google Analytics JavaScript individually from the pages that you want to track.

The key here is to only call google analytics if you are in a production environment! If you don’t, you will 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 application.

Source: Railscarma.com

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s