summaryrefslogtreecommitdiff
path: root/app/models/concerns/awardable.rb
blob: b4e3e9eb3ddbc3c6dbf7b66c9f0484bf97bbbc73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
module Awardable
  extend ActiveSupport::Concern

  included do
    has_many :award_emoji, as: :awardable, dependent: :destroy

    if self < Participable
      participant :award_emoji
    end
  end

  module ClassMethods
    def order_upvotes_desc
      order_votes_desc(AwardEmoji::UPVOTE_NAME)
    end

    def order_downvotes_desc
      order_votes_desc(AwardEmoji::DOWNVOTE_NAME)
    end

    def order_votes_desc(emoji_name)
      awardable_table = self.arel_table
      awards_table = AwardEmoji.arel_table

      join_clause = awardable_table.join(awards_table, Arel::Nodes::OuterJoin).on(
        awards_table[:awardable_id].eq(awardable_table[:id]).and(
          awards_table[:awardable_type].eq(self.name).and(
            awards_table[:name].eq(emoji_name)
          )
        )
      ).join_sources

      joins(join_clause).group(awardable_table[:id]).reorder("COUNT(award_emoji.id) DESC")
    end
  end

  def grouped_awards(with_thumbs = true)
    awards = award_emoji.group_by(&:name)

    if with_thumbs
      awards[AwardEmoji::UPVOTE_NAME]   ||= AwardEmoji.none
      awards[AwardEmoji::DOWNVOTE_NAME] ||= AwardEmoji.none
    end

    awards
  end

  def downvotes
    award_emoji.where(name: AwardEmoji::DOWNVOTE_NAME).count
  end

  def upvotes
    award_emoji.where(name: AwardEmoji::UPVOTE_NAME).count
  end

  def emoji_awardable?
    true
  end

  def awarded_emoji?(emoji_name, current_user)
    award_emoji.where(name: emoji_name, user: current_user).exists?
  end

  def create_award_emoji(name, current_user)
    return unless emoji_awardable?

    award_emoji.create(name: name, user: current_user)
  end

  def remove_award_emoji(name, current_user)
    award_emoji.where(name: name, user: current_user).destroy_all
  end

  def toggle_award_emoji(emoji_name, current_user)
    if awarded_emoji?(emoji_name, current_user)
      remove_award_emoji(emoji_name, current_user)
    else
      create_award_emoji(emoji_name, current_user)
    end
  end
end