Pages

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
 
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
 m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
 })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

 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
     });
    }
 });

})(jQuery);

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.

    $.ajax({
     type : 'get',
     url : url,
     data : {"curr_code": currency}
    }).done(function(){
         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.