Add Google Analytics to Ruby on Rails Application

Add Google Analytics to Ruby on Rails Application

Google Analytics is used by the vast majority of the internet to monitor traffic. You can quickly and easily add Google Analytics to your Rails application, however there are a few things you should pay attention to. First, make sure that the Analytics code only loads up in a production environment. It’s best to do this by first creating a partial called google_analytics and placing the following code inside of it:

app/views/layouts/_google_analytics.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<% if Rails.env == "production"  %>
  <script type="text/javascript">

    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-00000000-1']);
    _gaq.push(['_trackPageview']);

    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

  </script>
<% end %>

This code will tell Rails to only include the Analytics code in a production environment.

So far so good, That’s it!!! See ya!!! :)