Read about our upcoming Code of Conduct on this issue

award_emoji.rb 1.73 KB
Newer Older
1
2
# frozen_string_literal: true

3
class AwardEmoji < ApplicationRecord
4
5
  DOWNVOTE_NAME = "thumbsdown"
  UPVOTE_NAME   = "thumbsup"
6
7

  include Participable
8
  include GhostUser
9

10
  belongs_to :awardable, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
11
12
13
  belongs_to :user

  validates :awardable, :user, presence: true
14
  validates :name, presence: true, inclusion: { in: Gitlab::Emoji.emojis_names }
15
  validates :name, uniqueness: { scope: [:user, :awardable_type, :awardable_id] }, unless: :ghost_user?
16
17
18

  participant :user

19
20
21
22
  scope :downvotes, -> { named(DOWNVOTE_NAME) }
  scope :upvotes, -> { named(UPVOTE_NAME) }
  scope :named, -> (names) { where(name: names) }
  scope :awarded_by, -> (users) { where(user: users) }
23

24
25
26
  after_save :expire_etag_cache
  after_destroy :expire_etag_cache

27
28
  class << self
    def votes_for_collection(ids, type)
29
30
31
      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')
32
    end
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

    # 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
50
51
  end

52
53
54
55
56
57
58
  def downvote?
    self.name == DOWNVOTE_NAME
  end

  def upvote?
    self.name == UPVOTE_NAME
  end
59
60

  def expire_etag_cache
61
    awardable.try(:expire_etag_cache)
62
  end
63
end