Read about our upcoming Code of Conduct on this issue

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

3
4
5
6
7
class AwardEmoji < ActiveRecord::Base
  DOWNVOTE_NAME = "thumbsdown".freeze
  UPVOTE_NAME   = "thumbsup".freeze

  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
19
20
21

  participant :user

  scope :downvotes, -> { where(name: DOWNVOTE_NAME) }
  scope :upvotes,   -> { where(name: UPVOTE_NAME) }

22
23
24
  after_save :expire_etag_cache
  after_destroy :expire_etag_cache

25
26
  class << self
    def votes_for_collection(ids, type)
27
28
29
      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')
30
31
32
    end
  end

33
34
35
36
37
38
39
  def downvote?
    self.name == DOWNVOTE_NAME
  end

  def upvote?
    self.name == UPVOTE_NAME
  end
40
41

  def expire_etag_cache
42
    awardable.try(:expire_etag_cache)
43
  end
44
end