/
page_views_controller.rb
67 lines (51 loc) 路 2.5 KB
/
page_views_controller.rb
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
57
58
59
60
61
62
63
64
65
66
67
class PageViewsController < ApplicationMetalController
# ApplicationMetalController because we do not need all bells and whistles of ApplicationController.
# It should help performance.
include ActionController::Head
def create
page_view_create_params = if session_current_user_id
page_view_params.merge(user_id: session_current_user_id)
else
page_view_params.merge(counts_for_number_of_views: 10)
end
PageView.create(page_view_create_params)
update_article_page_views
head :ok
end
def update
if session_current_user_id
page_view = PageView.order(created_at: :desc).find_or_create_by(article_id: params[:id],
user_id: session_current_user_id)
unless page_view.new_record?
page_view.update_column(:time_tracked_in_seconds, page_view.time_tracked_in_seconds + 15)
end
end
head :ok
end
private
def update_article_page_views
return if Rails.env.production? && rand(15) != 1 # We don't need to update the article page views every time.
@article = Article.find(page_view_params[:article_id])
new_page_views_count = @article.page_views.sum(:counts_for_number_of_views)
@article.update_column(:page_views_count, new_page_views_count) if new_page_views_count > @article.page_views_count
update_organic_page_views
end
def page_view_params
params.slice(:article_id, :referrer, :user_agent)
end
def update_organic_page_views
return if Rails.env.production? && rand(100) != 1 # We need to do this operation only once in a while.
page_views_from_google_com = @article.page_views.where(referrer: "https://www.google.com/")
organic_count = page_views_from_google_com.sum(:counts_for_number_of_views)
if organic_count > @article.organic_page_views_count
@article.update_column(:organic_page_views_count,
organic_count)
end
organic_count_past_week_count = page_views_from_google_com
.where("created_at > ?", 1.week.ago).sum(:counts_for_number_of_views)
@article.update_column(:organic_page_views_past_week_count, organic_count_past_week_count)
organic_count_past_month_count = page_views_from_google_com
.where("created_at > ?", 1.month.ago).sum(:counts_for_number_of_views)
@article.update_column(:organic_page_views_past_month_count, organic_count_past_month_count)
end
end