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
14 self.enddate = read_attribute( :enddate ) || \
15 Time.now + 30.days - 1.second
19 if @candidate_names.length < 2
20 errors.add(nil, "You must list at least two candidates.")
23 @candidate_names.each do |c|
24 unless c.instance_of? String
25 errors.add(nil, "Candidates must be strings")
30 errors.add(nil, "Candidate name must not be empty")
33 end if @candidate_names
35 if @candidate_names and @candidate_names.uniq!
36 errors.add(nil, "Candidates must all be unique")
39 if name =~ /[^A-Za-z0-9]/
40 errors.add(:name, "must only include numbers and letters.")
43 errors.add(:name, "must not be a number")
46 if name =~ /^(create|index|confirm|change|results)$/
47 errors.add(:name, " is a reserved word.")
50 if enddate < startdate
51 errors.add(nil, "QuickVotes can't end before they start")
56 read_attribute( :name ).downcase() if read_attribute( :name )
63 def build_candidate_names
64 @candidate_names ||= []
65 if @candidate_names.empty? and not candidates.empty?
66 @candidate_names = candidates.collect {|c| c.name}
71 return unless errors.empty?
73 # delete the candidates
74 candidates.each {|c| c.destroy}
76 # create the new list based on the names
77 @candidate_names.each do |name|
78 candidate = Candidate.new({:name => name})
79 self.candidates << candidate
83 ### Convert a shortname or id into a QuickVote
84 def self.ident_to_quickvote(ident)
85 return nil unless ident
86 if ident.match(/^\d+$/)
87 quickvote = QuickVote.find(ident)
89 quickvote = QuickVote.find(:all, :conditions => ["name = ?", ident])[0]