Created
August 13, 2012 17:34
-
-
Save ryanlecompte/3342657 to your computer and use it in GitHub Desktop.
Using google_visualr for building generic charts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'google_visualr' | |
class ChartBuilder | |
# Creates a new builder instance. | |
def initialize(name, options = {}) | |
@name = name | |
@columns = options.fetch(:columns) { raise 'No columns defined' } | |
@chart = options.fetch(:chart) { raise 'No chart class defined' } | |
@chart_options = {:name => @name}.merge(options.fetch(:chart_options, {})) | |
@rows = [] | |
end | |
# Adds a new row to the builder. | |
def add(row) | |
@rows << row | |
end | |
alias_method :<<, :add | |
# Builds an HTML chart. | |
def build | |
<<-HTML | |
<!doctype html> | |
<html lang="en"> | |
<head> | |
<script src="http://www.google.com/jsapi"></script> | |
#{build_chart} | |
<meta charset="utf-8"> | |
<title>#{@name}</title> | |
</head> | |
<body> | |
<div id="chart"></div> | |
</body> | |
</html> | |
HTML | |
end | |
private | |
def build_chart | |
table = GoogleVisualr::DataTable.new | |
# setup columns | |
@columns.each do |column| | |
table.new_column(*column) | |
end | |
# setup rows | |
table.add_rows(@rows.size) | |
@rows.each_with_index do |row, row_index| | |
@columns.size.times do |col_index| | |
table.set_cell(row_index, col_index, row[col_index]) | |
end | |
end | |
chart = @chart.new(table, @chart_options) | |
chart.to_js('chart') | |
end | |
end | |
if __FILE__ == $0 | |
options = { | |
:chart => GoogleVisualr::Interactive::AreaChart, | |
:chart_options => {:width => 800, :height => 440}, | |
:columns => [ | |
['string', 'Year'], | |
['number', 'Sales'], | |
['number', 'Expenses'] | |
] | |
} | |
chart_builder = ChartBuilder.new('Company Performance', options) | |
[ | |
['2004', 1000, 400], | |
['2005', 1170, 460], | |
['2006', 660, 1120], | |
['2007', 1030, 540] | |
].each { |row| chart_builder << row } | |
puts chart_builder.build | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment