about summary refs log tree commit diff stats
path: root/app/models/concerns
diff options
context:
space:
mode:
Diffstat (limited to 'app/models/concerns')
-rw-r--r--app/models/concerns/votable.rb43
1 files changed, 43 insertions, 0 deletions
diff --git a/app/models/concerns/votable.rb b/app/models/concerns/votable.rb new file mode 100644 index 0000000..ba6e6d5 --- /dev/null +++ b/app/models/concerns/votable.rb
@@ -0,0 +1,43 @@
1module Votable
2 extend ActiveSupport::Concern
3
4 included do
5 has_many :votes, as: :votable
6
7 def already_upvoted?(ip)
8 !votes.where(ip: ip, upvote: 1).empty?
9 end
10
11 def already_downvoted?(ip)
12 !votes.where(ip: ip, upvote: 0).empty?
13 end
14
15 def upvote!(ip)
16 return false if already_upvoted?(ip)
17
18 if already_downvoted?(ip)
19 votes.where(ip: ip, upvote: 0).first.delete
20 self.downvotes -= 1
21 save!
22 else
23 votes.create(ip: ip, upvote: 1).save
24 self.upvotes += 1
25 save!
26 end
27 end
28
29 def downvote!(ip)
30 return false if already_downvoted?(ip)
31
32 if already_upvoted?(ip)
33 votes.where(ip: ip, upvote: 1).first.delete
34 self.upvotes -= 1
35 save!
36 else
37 votes.create(ip: ip, upvote: 0).save
38 self.downvotes += 1
39 save!
40 end
41 end
42 end
43end