acts_as_voter.rb
1.67 KB
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
# ActsAsVoter
module PeteOnRails
module Acts #:nodoc:
module Voter #:nodoc:
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_voter
has_many :votes, :as => :voter, :dependent => :nullify # If a voting entity is deleted, keep the votes.
include PeteOnRails::Acts::Voter::InstanceMethods
extend PeteOnRails::Acts::Voter::SingletonMethods
end
end
# This module contains class methods
module SingletonMethods
end
# This module contains instance methods
module InstanceMethods
# Usage user.vote_count(true) # All +1 votes
# user.vote_count(false) # All -1 votes
# user.vote_count() # All votes
#
def vote_count(for_or_against = "all")
return self.votes.size if for_or_against == "all"
self.votes.count(:conditions => {:vote => (for_or_against ? 1 : -1)})
end
def voted_for?(voteable)
voteable.voted_by?(self, true)
end
def voted_against?(voteable)
voteable.voted_by?(self, false)
end
def voted_on?(voteable)
voteable.voted_by?(self)
end
def vote_for(voteable)
self.vote(voteable, 1)
end
def vote_against(voteable)
self.vote(voteable, -1)
end
def vote(voteable, vote)
Vote.create(:vote => vote, :voteable => voteable, :voter => self).tap do |v|
voteable.reload_vote_counter if v.new_record? and voteable.respond_to?(:reload_vote_counter)
end.errors.empty?
end
end
end
end
end