about summary refs log tree commit diff stats
path: root/app/models/concerns/votable.rb
blob: ba6e6d5be34a142e2829b1884ce29af7f14b499c (plain) (blame)
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
module Votable
  extend ActiveSupport::Concern

  included do
    has_many :votes, as: :votable

    def already_upvoted?(ip)
      !votes.where(ip: ip, upvote: 1).empty?
    end

    def already_downvoted?(ip)
      !votes.where(ip: ip, upvote: 0).empty?
    end

    def upvote!(ip)
      return false if already_upvoted?(ip)

      if already_downvoted?(ip)
        votes.where(ip: ip, upvote: 0).first.delete
        self.downvotes -= 1
        save!
      else
        votes.create(ip: ip, upvote: 1).save
        self.upvotes += 1
        save!
      end
    end

    def downvote!(ip)
      return false if already_downvoted?(ip)

      if already_upvoted?(ip)
        votes.where(ip: ip, upvote: 1).first.delete
        self.upvotes -= 1
        save!
      else
        votes.create(ip: ip, upvote: 0).save
        self.downvotes += 1
        save!
      end
    end
  end
end