Class: Dashboards::Chart

Inherits:
Object
  • Object
show all
Defined in:
lib/dashboards/dsl/chart.rb

Constant Summary collapse

VALID_TYPES =
[:line, :pie, :column, :bar, :area, :scatter]
DEFAULT_HEIGHT =
'120px'
DEFAULT_COLOR =

White

'#FFFFFF'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name_or_options, options = {}) ⇒ Chart

Returns a new instance of Chart.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/dashboards/dsl/chart.rb', line 12

def initialize(name_or_options, options = {})
  if name_or_options.is_a?(Hash)
    @name = nil
    options = name_or_options
  else
    @name = name_or_options
  end
  @type = options.delete(:type) || :line
  @data = options.delete(:data)
  @options = options
  @options[:height] ||= options[:height] || DEFAULT_HEIGHT
  @options[:color] ||= DEFAULT_COLOR
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



5
6
7
# File 'lib/dashboards/dsl/chart.rb', line 5

def data
  @data
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/dashboards/dsl/chart.rb', line 5

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/dashboards/dsl/chart.rb', line 5

def options
  @options
end

#typeObject (readonly)

Returns the value of attribute type.



5
6
7
# File 'lib/dashboards/dsl/chart.rb', line 5

def type
  @type
end

Instance Method Details

#render(context) ⇒ Object

Raises:

  • (ArgumentError)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/dashboards/dsl/chart.rb', line 26

def render(context)
  data = @data.is_a?(Proc) ? context.instance_exec(&@data) : @data
  chartkick_method = chartkick_method(@type)

  options = @options.dup
  options[:title] = @name if @name

  # Apply color to different chart types
  case @type
  when :pie, :donut
    options[:colors] ||= [@options[:color]]
  when :column, :bar
    options[:colors] ||= [@options[:color]]
  else
    options[:dataset] ||= {
      borderColor: @options[:color],
      backgroundColor: @options[:color],
      pointBackgroundColor: @options[:color],
      pointBorderColor: @options[:color],
      pointHoverBackgroundColor: @options[:color],
      pointHoverBorderColor: @options[:color],
      hoverBackgroundColor: @options[:color],
      hoverBorderColor: @options[:color]
    }
  end

  # Apply height
  options[:height] = @options[:height]

  raise ArgumentError, "Invalid chart type: #{@type}" unless VALID_TYPES.include?(@type)

  if context.respond_to?(chartkick_method)
    context.public_send(chartkick_method, data, **options)
  else
    render_fallback(data)
  end
end