1 class QuickVote < Election
2 before_validation :build_candidate_names
3 after_validation :create_candidates
4 validates_uniqueness_of :name
6 attr_accessor :candidate_names
7 attr_accessor :reviewed
9 def initialize(params={})
11 self.startdate = Time.now
13 self.anonymous = 1 unless self.anonymous
17 if @candidate_names.length < 2
18 errors.add(nil, "You must list at least two candidates.")
21 @candidate_names.each do |c|
22 unless c.instance_of? String
23 errors.add(nil, "Candidates must be strings")
28 errors.add(nil, "Candidate name must not be empty")
31 end if @candidate_names
33 if @candidate_names and @candidate_names.uniq!
34 errors.add(nil, "Candidates must all be unique")
37 if name =~ /[^A-Za-z0-9]/
38 errors.add(:name, "must only include numbers and letters.")
41 errors.add(:name, "must not be a number")
44 if name =~ /^(create|index|confirm|change|results)$/
45 errors.add(:name, " is a reserved word.")
48 if enddate < startdate
49 errors.add(nil, "QuickVotes can't end before they start")
54 read_attribute( :name ).downcase() if read_attribute( :name )
61 def build_candidate_names
62 @candidate_names ||= []
63 if @candidate_names.empty? and not candidates.empty?
64 @candidate_names = candidates.collect {|c| c.name}
69 return unless errors.empty?
71 # delete the candidates
72 candidates.each {|c| c.destroy}
74 # create the new list based on the names
75 @candidate_names.each do |name|
76 candidate = Candidate.new({:name => name})
77 self.candidates << candidate
81 ### Convert a shortname or id into a QuickVote
82 def self.ident_to_quickvote(ident)
83 return nil unless ident
84 if ident.match(/^\d+$/)
85 quickvote = QuickVote.find(ident)
87 quickvote = QuickVote.find(:all, :conditions => ["name = ?", ident])[0]