merged in from code from the other master
[selectricity-live] / app / models / quick_vote.rb
1 class QuickVote < Election
2   before_validation :build_candidate_names
3   validates_uniqueness_of :name
4
5   attr_accessor :candidate_names
6   attr_accessor :reviewed
7   
8   def initialize(params={})
9     super
10     self.startdate = Time.now
11     self.active = 1
12     self.anonymous = 1 unless self.anonymous
13   end
14   
15   def validate
16     if @candidate_names.length < 2
17       errors.add(nil, "You must list at least two candidates.")
18     end
19
20     @candidate_names.each do |c|
21       unless c.instance_of? String
22         errors.add(nil, "Candidates must be strings")
23         next
24       end
25       c.strip!
26       if c.length == 0
27         errors.add(nil, "Candidate name must not be empty")
28         next
29       end
30     end if @candidate_names
31  
32     if @candidate_names and @candidate_names.uniq!
33       errors.add(nil, "Candidates must all be unique")
34     end
35
36     if name =~ /[^A-Za-z0-9]/
37       errors.add(:name, "must only include numbers and letters.")
38     end
39     if name =~ /^[0-9]+$/
40       errors.add(:name, "must not be a number")
41     end
42     
43     if name =~ /^(create|index|confirm|change|results)$/
44       errors.add(:name, " is a reserved word.")
45     end
46
47     if enddate < startdate
48       errors.add(nil, "QuickVotes can't end before they start")
49     end
50   end
51
52   def name
53     read_attribute( :name ).downcase() if read_attribute( :name )
54   end
55
56   def reviewed?
57     reviewed.to_i == 1
58   end
59
60   def build_candidate_names
61     @candidate_names ||= []
62     if @candidate_names.empty? and not self.candidates.empty?
63         @candidate_names = self.candidates.collect {|c| c.name}
64     end
65   end
66
67   def create_candidates
68     return unless errors.empty?
69     
70     # delete the candidates
71     candidates.each {|c| c.destroy}
72
73     # create the new list based on the names
74     @candidate_names.each do |name|
75       candidate = Candidate.new({:name => name})
76       self.candidates << candidate
77     end
78   end
79
80   ### Convert a shortname or id into a QuickVote
81   def self.ident_to_quickvote(ident)
82     return nil unless ident
83     if ident.match(/^\d+$/)
84       quickvote = QuickVote.find(ident)
85     else
86       quickvote = QuickVote.find(:all, :conditions => ["name = ?", ident])[0]
87     end
88
89     return quickvote
90   end
91 end

Benjamin Mako Hill || Want to submit a patch?