Google analytics statistics in Rails applications

Tram Ho

What is Google Analytics?

Google Analytics is one of the free seo tools provided by Google to collect data about the digital presence of your website. The main application of Google Analytics is to help website administrators understand user behavior, thereby offering deployment strategies to promote better sales:

  • Real-time statistics (real-time)
  • Statistics of the user’s access source, the language they use and the operating system of the user device
  • Specify user behavior on the website
  • Analyze traffic by demographics

Embed google analytics into your website

You can login to the page , complete the installation steps:

After completing the steps of declaring Google Analytics registration information on, Google requires you to agree to their terms and policies set you, You just need to tick the box and select the Accept button.

Then, embed the js script into the header in your application layout

Use google analytic api to keep track of user traffic

We will use the library

  • Add gem to gemfile:

Before starting the integration, you need to log in to google console developer, enable google analytic API and google analytic reporting API, create a project, service account and then add it to the google analytic account above. Instructions follow the link:

  • By default, the google API uses authenticate oauth2, so we will perform some steps to get access_token:

  • Then, use the access_token received to get site traffic statistics via the API

The response data will look like this:

  • Then extract the required data

Statistics print information about the post:


  • The final step is to run the rake task:


Share the news now

Source : Viblo