Method: GoogleVisualization#visualization

Defined in:
lib/google_visualization.rb

#visualization(id, chart_type, options = {}, &block) ⇒ Object

Call this method from the view to insert the visualization graph/chart here. This method will output a div with the specified id, and store the chart data to be rendered later via #render_visualizations

Parameters:

  • id (String)

    the id of the chart. corresponds to the id of the div

  • chart_type (String)

    the kind of chart to render

  • options (Hash) (defaults to: {})

    the configuration options for the graph



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/google_visualization.rb', line 57

def visualization(id, chart_type, options = {}, &block)
  init
  chart_type = chart_type.camelize      # Camelize the chart type, as the Google API follows Camel Case conventions (e.g. ColumnChart, MotionChart)
  options.stringify_keys!               # Ensure consistent hash access
  @visualization_packages << chart_type # Add the chart type to the packages needed to be loaded

  # Initialize the data table (with hashed options), and pass it the block for cleaner adding of attributes within the block
  table = Gvis::DataTable.new(options.delete("data"), options.delete("columns"), options)
  if block_given?
    yield table
  end

  html_options = options.delete("html") || {} # Extract the html options
  @google_visualizations.merge!(id => [chart_type, table, options]) # Store our chart in an instance variable to be rendered in the head tag

  # Output a div with given id on the page right now, that our graph will be embedded into
  html = html_options.collect {|key,value| "#{key}=\"#{value}\"" }.join(" ")
  concat raw(%Q(<div id="#{escape_id(id)}" #{html}><!-- /--></div>))
  nil # Return nil just incase this is called with an output erb tag, as we don't to output the html twice
end