Added Sparklines controller and dependency, see README. Created method and table...
[selectricity] / app / models / quick_vote.rb
1 class QuickVote < Election
2   after_validation :create_candidates
3   validates_uniqueness_of :name
4   validates_presence_of :name
5   attr_accessor :raw_candidates
6   attr_accessor :reviewed
7   
8   def validate
9     if not @raw_candidates or @raw_candidates.length < 2
10       errors.add(nil, "You must list at least two candidates.")
11     end
12     
13     @raw_candidates.each do |c|
14       unless c.instance_of? String
15         errors.add(nil, "Candidates must be strings")
16         next
17       end
18       c.strip!
19       if c.length == 0
20         errors.add(nil, "Candidate name must not be empty")
21         next
22       end
23     end if @raw_candidates
24
25     errors.add(nil, "Candidates must all be unique") if @raw_candidates and @raw_candidates.uniq!
26
27     if name =~ /[^A-Za-z0-9]/
28       errors.add(:name, "must only include numbers and letters.")
29     end
30     if name =~ /^[0-9]+$/
31       errors.add(:name, "must not be a number")
32     end
33     
34     if name =~ /^(create|index|confirm|change|results)$/
35       errors.add(:name, " is a reserved word.")
36     end
37   end
38   
39   def initialize(params={})
40     super
41     self.startdate = Time.now
42     self.enddate =  Time.now + 30.days
43     self.active = 1
44     self.anonymous = 1
45   end
46
47   def candidatelist=(candlist)
48     @raw_candidates = candlist
49   end
50
51   def name
52     read_attribute( :name ).downcase() if read_attribute( :name )
53   end
54
55   def reviewed?
56     reviewed.to_i == 1
57   end
58
59   def create_candidates
60     return unless errors.empty?
61     @raw_candidates.each do |name|
62       candidate = Candidate.new({:name => name})
63       self.candidates << candidate
64     end
65   end
66
67   ### Convert a shortname or id into a QuickVote
68   def self.ident_to_quickvote(ident)
69     return nil unless ident
70     if ident.match(/^\d+$/)
71       quickvote = QuickVote.find(ident)
72     else
73       quickvote = QuickVote.find(:all, :conditions => ["name = ?", ident])[0]
74     end
75
76     return quickvote
77   end
78 end

Benjamin Mako Hill || Want to submit a patch?