Fix a bug where quickvote displays name cant be blank twice. validators are inherited...
[selectricity-live] / app / models / quick_vote.rb
1 class QuickVote < Election
2   before_validation :build_candidate_names
3   after_validation :create_candidates
4   validates_uniqueness_of :name
5
6   attr_accessor :candidate_names
7   attr_accessor :reviewed
8   
9   def initialize(params={})
10     super
11     self.startdate = Time.now
12     self.active = 1
13     self.anonymous = 1 unless self.anonymous
14     self.enddate = read_attribute( :enddate ) || \
15                    Time.now + 30.days - 1.second
16   end
17   
18   def validate
19     if @candidate_names.length < 2
20       errors.add(nil, "You must list at least two candidates.")
21     end
22
23     @candidate_names.each do |c|
24       unless c.instance_of? String
25         errors.add(nil, "Candidates must be strings")
26         next
27       end
28       c.strip!
29       if c.length == 0
30         errors.add(nil, "Candidate name must not be empty")
31         next
32       end
33     end if @candidate_names
34  
35     if @candidate_names and @candidate_names.uniq!
36       errors.add(nil, "Candidates must all be unique")
37     end
38
39     if name =~ /[^A-Za-z0-9]/
40       errors.add(:name, "must only include numbers and letters.")
41     end
42     if name =~ /^[0-9]+$/
43       errors.add(:name, "must not be a number")
44     end
45     
46     if name =~ /^(create|index|confirm|change|results)$/
47       errors.add(:name, " is a reserved word.")
48     end
49
50     if enddate < startdate
51       errors.add(nil, "QuickVotes can't end before they start")
52     end
53   end
54
55   def name
56     read_attribute( :name ).downcase() if read_attribute( :name )
57   end
58
59   def reviewed?
60     reviewed.to_i == 1
61   end
62
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}
67     end
68   end
69
70   def create_candidates
71     return unless errors.empty?
72     
73     # delete the candidates
74     candidates.each {|c| c.destroy}
75
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
80     end
81   end
82
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)
88     else
89       quickvote = QuickVote.find(:all, :conditions => ["name = ?", ident])[0]
90     end
91
92     return quickvote
93   end
94 end

Benjamin Mako Hill || Want to submit a patch?