Thursday, 29 January 2015

Google analyicts wth Rails

  1. Go to google analytics
  1. Sign Up in google analytics and fill the useful information. it will generate the javascript code. Copy that javascript code.
  2. Now paste that javascript code into the app/views/layouts/application.html.erb just up from the end of the body tag </body>.
    The given layout is the layout which I am using for all pages.

        javascript code provided by google analytics
 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

 ga('create', 'UA-XXXX-XX', 'auto');
 ga('send', 'pageview');

  1. Most of the application are single page applications so it is necessary to keep track the ajax call also. so create a new file in app/assets/javascripts/ajax_pagetracker.js
Copy the below code into the file

(function ($) {
 $(document).ajaxSend(function(event, xhr, settings){
    if (typeof ga !== "undefined" && ga !== null) {
     ga('send', {
       'hitType': 'pageview',
       'page': settings.url


Note: Keep track the ajax calls via this method is not a better option at all because it will also track the other ajax calls like (loading the assets via ajax, loading the images via ajax). So keep track the images  and other calls  is not a better option at all. so we include tracking  code manually in every ajax. For ex.

     type : 'get',
     url : url,
     data : {"curr_code": currency}
         ga('send', {‘hitType': 'pageview', 'page':  url });
5. Include that file into the app/assets/javascripts/application.js. If you have used                      require_tree .   
than you don’t have need to include the file.
//= require ajax_pagetracker

6.  In rails 4, we also use turbolinks and google analytics doesn’t track the page loaded by the     turbolinks so follow the below steps for track the pages.

Create a new file in app/assets/javascripts/turbo_pagetracker.js

Paste the below code into the file.

$(document).on('page:change', function() {
 if (typeof ga !== "undefined" && ga !== null) {
    ga('send', {
     'hitType': 'pageview',
     'page': window.location.pathname

Also Include that file into app/assets/javascripts/application.js if require_tree is not available.

7. Now watch tracking of calls on the google analytics real time overview.