Skip to content

Instantly share code, notes, and snippets.

@Altech
Created September 23, 2012 18:50
Show Gist options
  • Save Altech/3772655 to your computer and use it in GitHub Desktop.
Save Altech/3772655 to your computer and use it in GitHub Desktop.
ruby way for cunstructing DataTable for Google Chart.
# thin warper of google_visualr (delegate the process of javascript conversion to it).
# I think :: Google_visualr is quite useful gem because it enable us to draw intractive chart on browser only using ruby. But it takes over the interface of JavaScript, especially setter and getter form. There is better way on ruby and we shold do so.
# basic - column first construction.
data = DataTable.new('label', 'score')
data << ['label1', 245]
data << ['label2', 2194]
# data += [['label1', 245], ['label2', 2194]] # other way.
data[2].v = ['label3', 314]
data[0][1].v = 246
data[0][0] # => Cell<@v=246>
data[0] # => Column<@v=['label1',246]>
# convert routine from ruby to js(google chart).
MAP = ->(v){
return case v
when Numeric
'number'
when String
'string'
when Boolean
'boolean'
when Date
'date'
when DateTime
'datetime'
# when ?
# 'timeofday'
else
raise "Error"
end
}
# table property (through using symbol, not integer)
data[:interactive] = true
data.properties # => {:interactive => true}
data.properties = ...
# column property
data[1][:width] = 240
data[1][:width] # => 240
# row property (use “inverse”)
inved_data = data.inv[1] # => Row<@v=>[246,2194,314]>
data.inv[1][:max] = 1000
# get size
data.size # => [2,3]
data.columns.size # => 2
data.rows.size # => 3
# delete columns(row)
data[2].delete!
data[2..3].delete!
# validate consistency including size, type. (only this wrapper)
data.validate
# advanced - row first construction(only to add inv).
data = DataTable.new('label', 'score').inv
# ...
# equality
data == data.inv # => true
# all primitive constructor is valid.
data = DataTable.new({
:cols => [ { :id => 'A', :label => 'NEW A' , :type => 'string' },
{ :id => 'B', :label => 'B-label', :type => 'number' },
{ :id => 'C', :label => 'C-label', :type => 'date' }
],
:rows => [ { :c => [ {:v => 'a'}, {:v => 1.0, :f => 'One'} , {:v => Date.parse('2008-02-28 00:31:26'), :f => '2/28/08 12:31 AM'} ] },
{ :c => [ {:v => 'b'}, {:v => 2.0, :f => 'Two'} , {:v => Date.parse('2008-03-30 00:31:26'), :f => '3/30/08 12:31 AM'} ] },
{ :c => [ {:v => 'c'}, {:v => 3.0, :f => 'Three'}, {:v => Date.parse('2008-04-30 00:31:26'), :f => '4/30/08 12:31 AM'} ] }
]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment