lib/db_graph/line.rb in grosser-db_graph-0.1.4 vs lib/db_graph/line.rb in grosser-db_graph-0.1.5
- old
+ new
@@ -31,11 +31,11 @@
def to_url
size = @options[:size] || '600x500'
GoogleChart::LineChart.new(size, nil, false) do |line|
for name, hash in data
- line.data(name, self.class.filled_and_sorted_values(hash, x_values), random_color)
+ line.data(name, klass.filled_and_sorted_values(hash, x_values), klass.color_for(name))
end
line.axis :x, :labels => x_labels
line.axis :y, :labels => y_labels
line.show_legend = (@options[:show_legend]!=false)
end.to_url
@@ -49,11 +49,11 @@
end
end
def y_labels
values = []
- data.each{|name,hash|values += self.class.filled_and_sorted_values(hash, x_values)}
+ data.each{|name,hash|values += klass.filled_and_sorted_values(hash, x_values)}
distribute_evently(values, NUM_Y_LABELS)
end
def self.url(style, model, attribute, options={})
g = self.new(style, :at=>options.delete(:at))
@@ -61,10 +61,14 @@
g.to_url
end
private
+ def klass
+ self.class
+ end
+
def x_values
case @style
when :minutes then 0..59
when :hours then 0..23
when :days then 1..31
@@ -72,18 +76,23 @@
when :months then 1..12
else raise "#{@style} is not supported"
end.to_a
end
- def random_color
- [1,2,3].map{ (('0'..'9').to_a + ('a'..'f').to_a)[rand(16)] * 2 } * ''
+ #determines a unique color based on a name
+ def self.color_for(name)
+ name = name.inspect + "some randomness for fun"
+ hash = (name.hash % 1_000_000_000).to_s #get a hash of a constant size
+ colors = [hash[0..1], hash[2..3], hash[4..5]].map{|c| c.to_f / 100.0 * 16} #use 3 parts of the hash to get numbers from 0 to 15.99
+ palette = ('0'..'9').to_a + ('a'..'f').to_a #hex values 0..f
+ colors.map{|c| palette[c.floor].to_s * 2} * '' #each color is duplicated and the joined
end
def interval_for(time)
interval_word = {:minutes=>:hour,:hours=>:day,:days=>:month,:weeks=>:year,:months=>:year}[@style]
raise "style #{@style} is not supported" unless interval_word
- start = self.class.at_beginning_of_interval(time, interval_word)
+ start = klass.at_beginning_of_interval(time, interval_word)
ende = start + 1.send(interval_word) - 1.second
[start, ende]
end
def self.at_beginning_of_interval(time, interval_type)
\ No newline at end of file