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 https://analytics.google.com/analytics/web/?pli=1#/ , 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 https://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/AnalyticsreportingV4/AnalyticsReportingService

  • 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:

https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py

  • 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:

Summarizing:

  • The final step is to run the rake task:

Source:

https://github.com/googleapis/google-api-ruby-client https://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/AnalyticsreportingV4/AnalyticsReportingService

https://hirozak.space/posts/get-popular-posts-from-google-analytics

Share the news now

Source : Viblo