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

Benjamin Mako Hill || Want to submit a patch?