* Renamed graphs_controller to graph_controller.
[selectricity-live] / app / controllers / graph_controller.rb
1 class GraphController < ApplicationController
2
3   # produce a graph of votes per day during an election
4   def votes_per_day
5     
6     @election = Election.find(params[:id])
7     data, labels = get_votes_per_day_data(@election)
8
9     line = Gruff::Line.new
10     line.title = "Voters Per Day"
11     line.font = File.expand_path('/usr/X11R6/lib/X11/fonts/TTF/Vera.ttf',
12                                  RAILS_ROOT)
13
14     line.data("#{@election.name}", data )
15     line.labels = labels
16
17     line.x_axis_label = "Date"
18     line.y_axis_label = "Number of Votes"
19     line.minimum_value = 0.0
20
21     line.draw
22     send_data(line.to_blob, :disposition => 'inline', :type => 'image/png')
23   end
24  
25   # generate the data and labels for each graph
26   def get_votes_per_day_data(election)
27
28     voter_times = Array.new
29     unique_days = Array.new
30     voters_per_day = Array.new
31     days_hash = Hash.new
32     
33     election.votes.each do |vote|
34       unless voter_times.any? {|utime| utime == vote.time}
35         voter_times << vote.time
36       end
37     end
38     
39     voter_times.sort!
40   
41     voter_times.each_with_index do |time, index| 
42       count = 1
43       # TODO: add comment
44       unless unique_days.any? { |d1| d1.eql?(time.mon.to_s + "/" + time.day.to_s) }
45         unique_days << (time.mon.to_s + "/" + time.day.to_s)
46         count += (voter_times[(index+1)..-1].find_all \
47           {|t| t.mon == time.mon && t.day == time.day}).size
48         voters_per_day << count
49       end      
50     end
51     
52     unique_days.each_with_index do |fmtdate, index|
53       days_hash[index] = fmtdate
54     end    
55
56     # return the data and the labels
57     return voters_per_day, days_hash
58    
59   end
60
61 end

Benjamin Mako Hill || Want to submit a patch?