Changed properties to remove unecessary exectables.
[selectricity-live] / app / models / vote.rb
1 class Vote < ActiveRecord::Base
2   # relationships to other classes
3   belongs_to :voter
4   has_many :rankings
5   has_one :token
6   
7   # callbacks
8   after_update :save_rankings
9   before_destroy :destroy_rankings
10
11   
12
13   def to_s
14     votes.join("")
15   end
16
17   def each
18     self.votes.each {|vote| yield vote}
19   end
20
21   def votes
22     unless @votes
23       if rankings.empty?
24         @votes = Array.new
25       else
26         @votes = rankings.sort.collect { |ranking| ranking.candidate.id }
27       end
28     end
29
30     @votes
31   end
32
33   def votes=(array)
34     @votes = array
35   end
36
37   def save_rankings
38     destroy_rankings
39     self.votes.each_with_index do |candidate_id, index| 
40       ranking = Ranking.new
41       ranking.rank = index
42       ranking.candidate =  Candidate.find(candidate_id)
43       self.rankings << ranking
44     end
45   end
46   
47   def destroy
48     self.destroy_rankings
49     super
50   end
51
52   def destroy_rankings 
53     rankings.each { |ranking| ranking.destroy }
54   end
55
56   def settime
57     self.time = Time.now
58     self.save
59   end
60
61   def confirm!
62     self.confirmed = 1
63     self.save
64     
65     unless self.voter.election.quickvote?
66       token.destroy and token.reload if token
67       self.token = Token.new
68       self.save
69     end
70   end
71
72   def confirm?
73     confirmed == 1
74   end
75   
76   def votestring=(string="")
77     candidate_ids = voter.election.candidates.sort.collect \
78       { |candidate| candidate.id.to_i }
79
80     rel_votes = string.split("").collect { |vote| vote.to_i }
81     
82     # covert relative orders to absolute candidate ids
83     self.votes = rel_votes.collect { |vote| candidate_ids[ vote - 1 ] }
84   end
85
86   def votestring
87     # create a mapping of candidates ids and the relative order of the
88     # candidates as they appear when sorted alphabetically
89     cand_relnums = {}
90     self.voter.election.candidates.sort.each_with_index do |c, i|
91       cand_relnums[c.id] = i + 1
92     end
93
94     # assemble the votestring
95     self.votes.collect {|v| cand_relnums[v]}.join("")
96   end
97
98   # the following subroutine is used for quickvotes. it creates a vote
99   # with the candidates listed in order of preference based on
100   # alphabetical order. it is meant to be manipulated and then confirmed
101   def set_defaults!
102     self.votes =  voter.election.candidates.sort.collect {|c| c.id }
103     self.save
104   end
105 end

Benjamin Mako Hill || Want to submit a patch?