2018-11-18 11:00:15 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-07-07 11:18:12 +05:30
|
|
|
class UserInteractedProject < ApplicationRecord
|
2021-03-11 19:13:27 +05:30
|
|
|
extend SuppressCompositePrimaryKeyWarning
|
|
|
|
|
2018-03-27 19:54:05 +05:30
|
|
|
belongs_to :user
|
|
|
|
belongs_to :project
|
|
|
|
|
|
|
|
validates :project_id, presence: true
|
|
|
|
validates :user_id, presence: true
|
|
|
|
|
|
|
|
CACHE_EXPIRY_TIME = 1.day
|
|
|
|
|
|
|
|
class << self
|
|
|
|
def track(event)
|
|
|
|
# For events without a project, we simply don't care.
|
|
|
|
# An example of this is the creation of a snippet (which
|
|
|
|
# is not related to any project).
|
|
|
|
return unless event.project_id
|
|
|
|
|
|
|
|
attributes = {
|
|
|
|
project_id: event.project_id,
|
|
|
|
user_id: event.author_id
|
|
|
|
}
|
|
|
|
|
2021-01-03 14:25:43 +05:30
|
|
|
cached_exists?(**attributes) do
|
2021-10-27 15:23:28 +05:30
|
|
|
where(attributes).exists? || UserInteractedProject.insert_all([attributes], unique_by: %w(project_id user_id))
|
|
|
|
true
|
2018-03-27 19:54:05 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def cached_exists?(project_id:, user_id:, &block)
|
|
|
|
cache_key = "user_interacted_projects:#{project_id}:#{user_id}"
|
|
|
|
Rails.cache.fetch(cache_key, expires_in: CACHE_EXPIRY_TIME, &block)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|