1 class QuickVote < Election
2 before_validation :build_candidate_names
3 after_validation :create_candidates
4 validates_uniqueness_of :name
5 validates_presence_of :name
7 attr_accessor :candidate_names
8 attr_accessor :reviewed
10 def initialize(params={})
12 self.startdate = Time.now
14 self.anonymous = 1 unless self.anonymous
15 self.enddate = read_attribute( :enddate ) || \
16 Time.now + 30.days - 1.second
20 if @candidate_names.length < 2
21 errors.add(nil, "You must list at least two candidates.")
24 @candidate_names.each do |c|
25 unless c.instance_of? String
26 errors.add(nil, "Candidates must be strings")
31 errors.add(nil, "Candidate name must not be empty")
34 end if @candidate_names
36 if @candidate_names and @candidate_names.uniq!
37 errors.add(nil, "Candidates must all be unique")
40 if name =~ /[^A-Za-z0-9]/
41 errors.add(:name, "must only include numbers and letters.")
44 errors.add(:name, "must not be a number")
47 if name =~ /^(create|index|confirm|change|results)$/
48 errors.add(:name, " is a reserved word.")
51 if enddate < startdate
52 errors.add(nil, "QuickVotes can't end before they start")
57 read_attribute( :name ).downcase() if read_attribute( :name )
64 def build_candidate_names
65 @candidate_names ||= []
66 if @candidate_names.empty? and not candidates.empty?
67 @candidate_names = candidates.collect {|c| c.name}
72 return unless errors.empty?
74 # delete the candidates
75 candidates.each {|c| c.destroy}
77 # create the new list based on the names
78 @candidate_names.each do |name|
79 candidate = Candidate.new({:name => name})
80 self.candidates << candidate
84 ### Convert a shortname or id into a QuickVote
85 def self.ident_to_quickvote(ident)
86 return nil unless ident
87 if ident.match(/^\d+$/)
88 quickvote = QuickVote.find(ident)
90 quickvote = QuickVote.find(:all, :conditions => ["name = ?", ident])[0]