Adding google analytics to a rails app

I wanted to add google analytics code to my rails app which I think a bit more work compared to just adding javascript code directly to a static HTML site. After some digging I found out it can be done two ways.

1. Just add the javascript code to app/helpers/application_helper.rb

2. Or by installing a gem from github

A. By adding the javascript code

1. Add the following javascript code to app/helper/application_helper.rb

 <% def google_analytics_js %>

'<script type="text/javascript">

var _gaq = _gaq || [];

_gaq.push(['_setAccount', 'UA-xxxxxxxx-y']);

_gaq.push(['_trackPageview']);

(function() {

var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;

ga.src = ('https:' == document.location.protocol ? '<a href="https://ssl/">https://ssl</a>' : '<a href="http://www/">http://www</a>') + '.<a href="http://google-analytics.com/ga.js">google-analytics.com/ga.js</a>';

var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

})();

</script>'

<% end %>

2. Replace the ‘UA-xxxxxxxx-y’ in the code above with the tracking ID. Save and close application_helper.rb.

3. Add  <%= google_analytics_js %>  to the the file, just before the closing “</head>” HTML tag on each page.

This is ok if there are few pages in an app. But it will be tedious to go and change in each file for a larger application. That is where the gem come handy.

 B. By adding a gem in rails app

1. Add the following to your Gemfile:

gem ‘google-analytics-rails’
Then run:

bundle install

2. Go to file config/environments/production.rb:

# replace this with your tracker code
GA.tracker = “UA-xxxxxx-x”

3. And go to app/views/layout/application.html.erb, in the <head> tag :

Add

<%= analytics_init if Rails.env.production? %>

That should do the trick.