cluster configuration for new machine
[selectricity] / 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   end
15   
16   def validate
17     if @candidate_names.length < 2
18       errors.add(nil, "You must list at least two candidates.")
19     end
20
21     @candidate_names.each do |c|
22       unless c.instance_of? String
23         errors.add(nil, "Candidates must be strings")
24         next
25       end
26       c.strip!
27       if c.length == 0
28         errors.add(nil, "Candidate name must not be empty")
29         next
30       end
31     end if @candidate_names
32  
33     if @candidate_names and @candidate_names.uniq!
34       errors.add(nil, "Candidates must all be unique")
35     end
36
37     if name =~ /[^A-Za-z0-9]/
38       errors.add(:name, "must only include numbers and letters.")
39     end
40     if name =~ /^[0-9]+$/
41       errors.add(:name, "must not be a number")
42     end
43     
44     if name =~ /^(create|index|confirm|change|results)$/
45       errors.add(:name, " is a reserved word.")
46     end
47
48     if enddate < startdate
49       errors.add(nil, "QuickVotes can't end before they start")
50     end
51   end
52
53   def name
54     read_attribute( :name ).downcase() if read_attribute( :name )
55   end
56
57   def reviewed?
58     reviewed.to_i == 1
59   end
60
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}
65     end
66   end
67
68   def create_candidates
69     return unless errors.empty?
70     
71     # delete the candidates
72     candidates.each {|c| c.destroy}
73
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
78     end
79   end
80
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)
86     else
87       quickvote = QuickVote.find(:all, :conditions => ["name = ?", ident])[0]
88     end
89
90     return quickvote
91   end
92 end

Benjamin Mako Hill || Want to submit a patch?