Google Analytics track in ruby on Rails application


There are several ways/language  to track your website. Here we discuss how to use it is ruby project.
Solution 1:
In Ruby, you can put the script below in the specific webpage to track only that page: rubyproject/app/views/webpagename/show.html.haml file
: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"));
:javascript
  try{
    var pageTracker = _gat._getTracker("$GOOGLE_ANALYTICS_ID");
    pageTracker._trackPageview();

  } catch(err) {}

Solution 2:
If you want to track all your webpages, 
Step 1 : create a new haml file in the path:

app/views/shared/_google_analytics.html.haml

-For the local usage, development environment, in this _google_analytics.html.haml file: 
:javascript
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-46071281-1']);
  _gaq.push(['_setDomainName', 'none']);

  _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/u/ga_debug.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

-For the live website usage, production environment, in this _google_analytics.html.haml file:
 :javascript
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-46071281-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);
  })();

Step 2:  Add the  "partial" in the file: 

app/views/layouts/application.html.haml

#main{:role => "main"}
 ...
 = render :partial => 'shared/google_analytics'
Note: 
1. The GA render must be at the last line.
2. "Indent" must be aligned.

reference:
ga explanation on google
ga_code for ruby

Comments

Popular posts from this blog

install ipython in Cloudera VM using pip

install postgreSQL in ubuntu 16.04

Install MYSQL 5.6 in ubuntu 12.04/14.04 and set password and remote access