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:
1 2 | gem 'google-api-client' |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # lib/tasks/analytics.rake require 'google/apis/analyticsreporting_v4' require 'google/api_client/auth/key_utils' namespace :analytics do desc 'get popular posts from google analytics' task popular_posts: :environment do keyfile = Rails.root.join('google_analytics.p12') analytics = Google::Apis::AnalyticsreportingV4 client = analytics::AnalyticsReportingService.new client.authorization = Signet::OAuth2::Client.new( token_credential_uri: 'https://accounts.google.com/o/oauth2/token', audience: 'https://accounts.google.com/o/oauth2/token', scope: 'https://www.googleapis.com/auth/analytics.readonly', issuer: ENV['GA_ISSUER'], signing_key: Google::APIClient::KeyUtils.load_from_pkcs12(keyfile, ENV['GA_KEY_SECRET']) ) client.authorization.fetch_access_token! end end |
- Then, use the access_token received to get site traffic statistics via the API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | view_id = ENV['GA_VIEW_ID'] metric = analytics::Metric.new(expression: 'ga:pageviews', alias: 'pageviews') dimension = analytics::Dimension.new(name: 'ga:pagePath') date_range = analytics::DateRange.new(start_date: '7DaysAgo', end_date: 'today') order_by = analytics::OrderBy.new(field_name: 'ga:pageviews', sort_order: 'DESCENDING') request = analytics::GetReportsRequest.new( report_requests: [analytics::ReportRequest.new( view_id: view_id, metrics: [metric], dimensions: [dimension], date_ranges: [date_range], order_bys: [order_by] )] ) response = client.batch_get_reports(request) |
1 2 3 4 5 6 7 8 9 10 11 12 | request = analytics::GetReportsRequest.new( report_requests: [analytics::ReportRequest.new( view_id: view_id, metrics: [metric], dimensions: [dimension], date_ranges: [date_range], order_bys: [order_by] )] ) response = client.batch_get_reports(request) data = response.reports.first.data |
The response data will look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | => #<Google::Apis::AnalyticsreportingV4::ReportData:0x00007ffab8642ef8 @maximums=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab8641fd0 @values=["67"]>], @minimums=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab8640ef0 @values=["1"]>], @row_count=31, @rows= [#<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffabab77930 @dimensions=["/posts/rails-blog"], @metrics= [#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffabab75ea0 @values=["67"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab864bf30 @dimensions=["/"], @metrics= [#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab864b5d0 @values=["30"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab864acc0 @dimensions=["/posts/23-years-old-blog"], @metrics= [#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab864a360 @values=["12"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab8649a50 @dimensions=["/posts/free-domain-and-https-heroku"], @metrics= [#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab86490f0 @values=["11"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab86487e0 @dimensions=["/posts/make-markdown-editor"], @metrics=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffabab6fb40 @values=["8"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffabab6c5d0 @dimensions=["/posts/axios-token-configure"], @metrics=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab8653708 @values=["7"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab8652df8 @dimensions=["/about"], @metrics=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab8652498 @values=["6"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab8651b88 @dimensions=["/categories/Life"], @metrics=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab8651228 @values=["4"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab8650918 @dimensions=["/tags"], @metrics=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffabab67f08 @values=["4"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffabab66568 @dimensions=["/categories/tech"], @metrics=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab865ba48 @values=["3"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab865b138 @dimensions=["/posts/boiler-room-home-theater"], @metrics=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab865a7d8 @values=["3"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab8659ec8 @dimensions=["/categories/Gadgets"], @metrics=[#<Google::Apis::AnalyticsreportingV4::DateRangeValues:0x00007ffab8659568 @values=["2"]>]>, #<Google::Apis::AnalyticsreportingV4::ReportRow:0x00007ffab8658c58 @dimensions=["/categories/Music"], |
- Then extract the required data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | num = 0 data.rows.each do |row| next unless row.dimensions.to_s.include?('/posts/') slug = row.dimensions.first.to_s[7..-1] post = Post.find_by(slug: slug) next if post.nil? num += 1 popular_post = PopularPost.where(rank: num).first_or_create! do |new_popular_post| new_popular_post.rank = num new_popular_post.post = post end popular_post.update!(post_id: post.id) puts "#{num}: #{row.metrics.first.values.first}views: #{post.title}" break if num == 8 end |
1 2 3 4 5 6 7 8 9 10 11 | #popular_post.rb #t.integer "rank", null: false #t.bigint "post_id" #t.datetime "created_at", null: false #t.datetime "updated_at", null: false #t.index ["post_id"], name: "index_popular_posts_on_post_id" class PopularPost < ApplicationRecord belongs_to :post end |
Statistics print information about the post:
1 2 3 4 5 6 7 8 | 1: 67views: Railsでブログを作ってみた 2: 12views: 23歳はブログを少しずつでも書こうと思う 3: 11views: 無料でドメイン割り当て、HTTPSを実現。Heroku + Cloudflare 4: 8views: 3分でマークダウンエディターを作る【UIkit】 5: 7views: axiosのヘッダーにtokenを埋め込んで常時使えるようにする 6: 3views: Boiler Roomをお酒片手にプロジェクターで観ると幸せになれる 7: 2views: 奇跡の自然、モハーの断崖。まさに世界の果て 【旅ログ】 |
Summarizing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | require 'google/apis/analyticsreporting_v4' require 'google/api_client/auth/key_utils' namespace :analytics do desc 'get popular posts from google analytics' task popular_posts: :environment do keyfile = Rails.root.join('google_analytics.p12') analytics = Google::Apis::AnalyticsreportingV4 client = analytics::AnalyticsReportingService.new client.authorization = Signet::OAuth2::Client.new( token_credential_uri: 'https://accounts.google.com/o/oauth2/token', audience: 'https://accounts.google.com/o/oauth2/token', scope: 'https://www.googleapis.com/auth/analytics.readonly', issuer: ENV['GA_ISSUER'], signing_key: Google::APIClient::KeyUtils.load_from_pkcs12(keyfile, ENV['GA_KEY_SECRET']) ) client.authorization.fetch_access_token! view_id = ENV['GA_VIEW_ID'] metric = analytics::Metric.new(expression: 'ga:pageviews', alias: 'pageviews') dimension = analytics::Dimension.new(name: 'ga:pagePath') date_range = analytics::DateRange.new(start_date: '7DaysAgo', end_date: 'today') order_by = analytics::OrderBy.new(field_name: 'ga:pageviews', sort_order: 'DESCENDING') request = analytics::GetReportsRequest.new( report_requests: [analytics::ReportRequest.new( view_id: view_id, metrics: [metric], dimensions: [dimension], date_ranges: [date_range], order_bys: [order_by] )] ) response = client.batch_get_reports(request) data = response.reports.first.data num = 0 data.rows.each do |row| next unless row.dimensions.to_s.include?('/posts/') slug = row.dimensions.first.to_s[7..-1] post = Post.find_by(slug: slug) next if post.nil? num += 1 popular_post = PopularPost.where(rank: num).first_or_create! do |new_popular_post| new_popular_post.rank = num new_popular_post.post = post end popular_post.update!(post_id: post.id) puts "#{num}: #{row.metrics.first.values.first}views: #{post.title}" break if num == 8 end end end |
- The final step is to run the rake task:
1 2 | bundle exec rake analytics:popular_posts |
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