1. Create _google_analytics.html.erb view:
<!– Google Analytics –>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
// Create tracker.
ga(‘create’, ‘<%= ENV[‘GOOGLE_ANALYTICS_TRACKING_ID’] %>’, ‘auto’);
<!– End Google Analytics –>
This code download Google Analytics code and set up a tracker. Understand Google Analytics trackers
Here we set the tracking ID as an environment variable, so that we could set up different Google Analytics accounts for different environments.
2. Set up the tracking ID environment variable.
2.1 For local environment: Add GOOGLE_ANALYTICS_TRACKING_ID=UA-XXXXXXX-X in .env file
2.2 For remote environments: Add GOOGLE_ANALYTICS_TRACKING_ID=UA-XXXXXXX-X to files under config/environments files. Example files listed as follows:
3. Add Google Analytics view to application layout:
In order to use Google Analytics for all the pages in our site, add this to application.html.erb
<head>
<!– Only set up google analytics when running in certain environments–>
<% if %w(development production).include? Rails.env %>
<%= render partial: ‘shared/google_analytics’ %>
<% end %>
</head>
4. Add track pageview code in a separate javascript file:
Here we create a separate javascript file instead of just adding the code in the view, with the consideration that we might need to add other tracking code later, such as form event tracking.
To understand how to custom pageview, check out this instruction page
(function() {
// If google analytics is not set up, skip tracking code
if(window.ga === undefined) return;
//// Track page view
// Set the page value on the tracker. Url: get rid of parameters and trailing ‘/’
ga(‘set’, ‘page’, document.location.pathname.split(‘?’)[0]);
// Send page view
ga(‘send’, ‘pageview’);
})();