docbrown/app/controllers/page_views_controller.rb
Jeremy Friesen 5ec47d99dc
Ensuring we don't track views of author or unpublished (#16143)
* Ensuring we don't track views of author or unpublished

Prior to this commit, I was surprised to learn that we:

1) Tracked an author's view of their article.
2) Tracked views of an unpublished article.

This came up from a Forem creator asking if they could reset the view
counter.  Or trigger the reset on publication.

I think a general business logic policy of don't track views for the
author and don't track views for unpublished articles is a reasonable
default.

Were we to pursue the clear views on publication, we'd need to consider
something that went from unpublished -> published -> unpublished ->
published.  Without a more explicit state machine, triggering a
busineiss logic behavior seems a bit unexpected.

In other words, I wrote an article.  There are 20 views when I realize
that I need to unpublished it.  I make the changes in the unpublished
state, and re-publish.  I'd assume that those 20 views would still be
"recorded" and counted towards my article's view counts.

* Adjusting condition structure

Prior to this commit, the `if` clause was rather far to the right.  This
helps make the if clause more pronounced.
2022-01-18 11:23:18 -05:00

40 lines
1.6 KiB
Ruby

class PageViewsController < ApplicationMetalController
# ApplicationMetalController because we do not need all bells and whistles of ApplicationController.
# It should help performance.
include ActionController::Head
# Each time we have a non-authenticated visitor, we have a 10% chance that we will record that
# specific impression as a page view. When we do record that specific impression as a page view,
# we want to give credit for all likely page views that we didn't record (e.g., the 90% or so).
#
# @note Yes, this is a very verbose constant name. Apologies, don't type it. But I [@jeremyf]
# want it here to explain a magic number.
#
# @see https://github.com/forem/forem/blob/main/app/assets/javascripts/initializers/initializeBaseTracking.js.erb#L113-L117
# @see https://github.com/forem/forem/pull/12686#discussion_r577271589 for further discussion.
VISITOR_IMPRESSIONS_AGGREGATE_COUNTS_FOR_NUMBER_OF_VIEWS = 10
def create
page_view_create_params = params.slice(:article_id, :referrer, :user_agent)
if session_current_user_id
page_view_create_params[:user_id] = session_current_user_id
else
page_view_create_params[:counts_for_number_of_views] = VISITOR_IMPRESSIONS_AGGREGATE_COUNTS_FOR_NUMBER_OF_VIEWS
end
Articles::UpdatePageViewsWorker.perform_at(
2.minutes.from_now,
page_view_create_params,
)
head :ok
end
def update
if session_current_user_id
Articles::PageViewUpdater.call(article_id: params[:id], user_id: session_current_user_id)
end
head :ok
end
end