]> projects.mako.cc - selectricity/blob - app/models/vote.rb
7678f5463900034de67c6ff2dff60c2d281a059c
[selectricity] / 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   def to_s
12     votes.join("")
13   end
14
15   def each
16     votes.each {|vote| yield vote}
17   end
18
19   def votes
20     unless @votes
21       if rankings.empty?
22         @votes = Array.new
23       else
24         @votes = rankings.sort.collect { |ranking| ranking.candidate.id }
25       end
26     end
27
28     @votes
29   end
30
31   def votes=(array)
32     @votes = array
33   end
34
35   def save_rankings
36     destroy_rankings
37     self.votes.each_with_index do |candidate, index| 
38       ranking = Ranking.new
39       ranking.rank = index
40       ranking.candidate =  Candidate.find(candidate)
41       self.rankings << ranking
42     end
43   end
44
45   def destroy_rankings 
46     rankings.each { |ranking| ranking.destroy }
47   end
48
49   def confirm!
50     self.confirmed = 1
51     self.save
52     
53     unless self.voter.election.quickvote?
54       token.destroy and token.reload if token
55       self.token = Token.new
56       self.save
57     end
58   end
59
60   def confirm?
61     confirmed == 1
62   end
63   
64   def votestring=(string="")
65     candidate_ids = voter.election.candidates.sort.collect \
66       { |candidate| candidate.id.to_i }
67
68     rel_votes = string.split("").collect { |vote| vote.to_i }
69     
70     # covert relative orders to absolute candidate ids
71     self.votes = rel_votes.collect { |vote| candidate_ids[ vote - 1 ] }
72   end
73
74 end

Benjamin Mako Hill || Want to submit a patch?