discourse/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_extension.rb
Jarek Radosz 8baf4d5d4c
DEV: Enable Style/RedundantSelf rubocop rule (#40098)
(to be enabled in the shared config)
2026-05-19 19:27:45 +02:00

55 lines
1.5 KiB
Ruby
Vendored

# frozen_string_literal: true
module DiscourseTopicVoting
module TopicExtension
extend ActiveSupport::Concern
prepended do
has_one :topic_vote_count,
class_name: "DiscourseTopicVoting::TopicVoteCount",
dependent: :destroy
has_many :votes, class_name: "DiscourseTopicVoting::Vote", dependent: :destroy
attribute :current_user_voted
end
def can_vote?
@can_vote ||=
SiteSetting.topic_voting_enabled && regular? && Category.can_vote?(category_id) &&
category && category.topic_id != id
end
def vote_count
topic_vote_count&.votes_count.to_i
end
def user_voted?(user)
if current_user_voted
current_user_voted == 1
else
votes.map(&:user_id).include?(user.id)
end
end
def update_vote_count
count = votes.count
DB.exec(<<~SQL, topic_id: id, votes_count: count)
INSERT INTO topic_voting_topic_vote_count
(topic_id, votes_count, created_at, updated_at)
VALUES
(:topic_id, :votes_count, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON CONFLICT (topic_id) DO UPDATE SET
votes_count = :votes_count,
updated_at = CURRENT_TIMESTAMP
WHERE topic_voting_topic_vote_count.topic_id = :topic_id
SQL
end
def who_voted(limit: DiscourseTopicVoting::VOTER_PREVIEW_LIMIT)
return if !SiteSetting.topic_voting_show_who_voted
votes.active.includes(:user).order(created_at: :desc).limit(limit).filter_map(&:user)
end
end
end