debian-mirror-gitlab/app/models/award_emoji.rb

69 lines
1.9 KiB
Ruby
Raw Normal View History

2018-11-18 11:00:15 +05:30
# frozen_string_literal: true
2019-07-07 11:18:12 +05:30
class AwardEmoji < ApplicationRecord
2019-12-04 20:38:33 +05:30
DOWNVOTE_NAME = "thumbsdown"
UPVOTE_NAME = "thumbsup"
include Participable
2017-08-17 22:00:37 +05:30
include GhostUser
2019-12-26 22:10:19 +05:30
include Importable
2017-09-10 17:25:29 +05:30
belongs_to :awardable, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
belongs_to :user
2019-12-26 22:10:19 +05:30
validates :user, presence: true
validates :awardable, presence: true, unless: :importing?
2016-08-24 12:49:21 +05:30
validates :name, presence: true, inclusion: { in: Gitlab::Emoji.emojis_names }
2020-04-22 19:07:51 +05:30
validates :name, uniqueness: { scope: [:user, :awardable_type, :awardable_id] }, unless: -> { ghost_user? || importing? }
participant :user
2019-12-04 20:38:33 +05:30
scope :downvotes, -> { named(DOWNVOTE_NAME) }
scope :upvotes, -> { named(UPVOTE_NAME) }
scope :named, -> (names) { where(name: names) }
scope :awarded_by, -> (users) { where(user: users) }
2021-09-30 23:02:18 +05:30
after_save :expire_cache
after_destroy :expire_cache
2018-03-17 18:26:18 +05:30
2017-08-17 22:00:37 +05:30
class << self
def votes_for_collection(ids, type)
2017-09-10 17:25:29 +05:30
select('name', 'awardable_id', 'COUNT(*) as count')
.where('name IN (?) AND awardable_type = ? AND awardable_id IN (?)', [DOWNVOTE_NAME, UPVOTE_NAME], type, ids)
.group('name', 'awardable_id')
2017-08-17 22:00:37 +05:30
end
2018-11-20 20:47:30 +05:30
# Returns the top 100 emoji awarded by the given user.
#
# The returned value is a Hash mapping emoji names to the number of times
# they were awarded:
#
# { 'thumbsup' => 2, 'thumbsdown' => 1 }
#
# user - The User to get the awards for.
# limt - The maximum number of emoji to return.
def award_counts_for_user(user, limit = 100)
limit(limit)
.where(user: user)
.group(:name)
.order('count_all DESC, name ASC')
.count
end
2017-08-17 22:00:37 +05:30
end
def downvote?
self.name == DOWNVOTE_NAME
end
def upvote?
self.name == UPVOTE_NAME
end
2018-03-17 18:26:18 +05:30
2021-09-30 23:02:18 +05:30
def expire_cache
awardable.try(:bump_updated_at)
2018-03-17 18:26:18 +05:30
awardable.try(:expire_etag_cache)
2021-09-30 23:02:18 +05:30
awardable.try(:update_upvotes_count) if upvote?
2018-03-17 18:26:18 +05:30
end
end