]> projects.mako.cc - selectricity/blob - app/models/quick_vote.rb
Import latest subversion RubyVote.
[selectricity] / app / models / quick_vote.rb
1 class QuickVote < Election
2   after_validation :create_candidates
3   validates_uniqueness_of :name
4   attr_accessor :raw_candidates
5   attr_accessor :reviewed
6   attr_accessor :plurality_result
7   attr_accessor :approval_result
8   attr_accessor :condorcet_result
9   attr_accessor :ssd_result
10   attr_accessor :borda_result
11
12   def validate
13     if @raw_candidates.length < 2
14       errors.add("You must list at least two candidates.")
15     end
16
17     if name =~ /[^A-Za-z0-9]/
18       errors.add("The name must only include numbers and letters.")
19     end
20   end
21   
22   def initialize(params={})
23     super
24     self.startdate = Time.now
25     self.enddate =  Time.now + 30.days
26     self.active = 1
27     self.anonymous = 1
28   end
29
30   def candidatelist=(candlist)
31     @raw_candidates = candlist
32   end
33
34   def name
35     read_attribute( :name ).downcase()
36   end
37
38   def reviewed?
39     reviewed.to_i == 1
40   end
41
42   def create_candidates
43     @raw_candidates.each do |name|
44       candidate = Candidate.new({:name => name})
45       self.candidates << candidate
46     end
47   end
48
49   #Calculate Election Results
50   def results
51     # initalize the tallies to empty arrays
52     preference_tally = Array.new
53     plurality_tally = Array.new
54     approval_tally = Array.new
55
56     self.voters.each do |voter|
57       # skip if the voter has not voted or has an unconfirmed vote
58       next unless voter.voted?
59
60       plurality_tally << voter.vote.rankings.sort[0].candidate.id
61       approval_tally << voter.vote.rankings.sort[0..1].collect \
62         { |ranking| ranking.candidate.id }
63       preference_tally << voter.vote.rankings.sort.collect \
64         { |ranking| ranking.candidate.id }
65     end
66     @plurality_result = PluralityVote.new(plurality_tally).result
67     @approval_result = ApprovalVote.new(approval_tally).result
68     @condorcet_result = PureCondorcetVote.new(preference_tally).result
69     @ssd_result = CloneproofSSDVote.new(preference_tally).result
70     @borda_result = BordaVote.new(preference_tally).result
71     #@runoff_result = InstantRunoffVote.new(preference_tally).result
72     #@runoff_results = PluralityVote.new(preference_tally).result
73
74   end
75
76   ### Convert a shortname or id into a QuickVote
77   def self.ident_to_quickvote(ident)
78     if ident.match(/^\d+$/)
79       quickvote = QuickVote.find(ident)
80     else
81       quickvote = QuickVote.find_all(["name = ?", ident])[0]
82     end
83
84     return quickvote
85   end
86 end

Benjamin Mako Hill || Want to submit a patch?