Class: DBGraph::Line

Inherits:
Object
  • Object
show all
Defined in:
lib/db_graph/line.rb

Constant Summary collapse

NUM_Y_LABELS =
10

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(style, options = {}) ⇒ Line

Returns a new instance of Line.



10
11
12
13
14
# File 'lib/db_graph/line.rb', line 10

def initialize(style, options={})
  @style = style.to_sym
  @options = options
  self.data = {}
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



8
9
10
# File 'lib/db_graph/line.rb', line 8

def data
  @data
end

Class Method Details

.url(style, model, attribute, options = {}) ⇒ Object



58
59
60
61
62
# File 'lib/db_graph/line.rb', line 58

def self.url(style, model, attribute, options={})
  g = self.new(style, :at=>options.delete(:at))
  g.add model, attribute, options
  g.to_url
end

Instance Method Details

#add(model, attribute, options = {}) ⇒ Object



16
17
18
19
# File 'lib/db_graph/line.rb', line 16

def add(model, attribute, options={})
  label = options.delete(:label) || "#{model} #{attribute}"
  data[label] = count(model, attribute, options)
end

#count(model, attribute, options = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/db_graph/line.rb', line 21

def count(model, attribute, options={})
  scope = if @options[:at]
    start, ende = interval_for(@options[:at])
    model.scoped(:conditions=>["#{attribute} BETWEEN ? AND ?", start, ende]).scoped(options)
  else
    model.scoped(options)
  end
  data_type = @style.to_s.sub(/s$/,'').upcase
  scope.count(:group=>"#{data_type}(#{attribute})")
end

#to_urlObject



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/db_graph/line.rb', line 32

def to_url
  size = @options[:size] || '600x500'
  GoogleChart::LineChart.new(size, nil, false) do |line|
    for name, hash in data
      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
end

#x_labelsObject



44
45
46
47
48
49
50
# File 'lib/db_graph/line.rb', line 44

def x_labels
  case @style
  when :days then x_values.map{|x|x%5==0 ? x : ''}
  when :weeks, :minutes then x_values.map{|x|x%10==0 ? x : ''}
  else x_values
  end
end

#y_labelsObject



52
53
54
55
56
# File 'lib/db_graph/line.rb', line 52

def y_labels
  values = []
  data.each{|name,hash|values += klass.filled_and_sorted_values(hash, x_values)}
  distribute_evently(values, NUM_Y_LABELS)
end