class HTML_Table

Public Class Methods

new(arrData,opts={}) click to toggle source
# File lib/html_table.rb, line 8
def initialize(arrData,opts={})

  @sort_code =
    if opts[:hashSort].nil?
      ''
    else
      #"data.sort([{column: 1, desc:true}]);"
      "data.sort([{column: #{opts[:hashSort][:col_number]}, desc:#{opts[:hashSort][:descending]}}]);"
    end

  @format_code =
    if opts[:hashFormat].nil?
      ''
    else
      #"var formatter = new google.visualization.BarFormat({width: 60}); formatter.format(data, 1);"
      "var formatter = new google.visualization.#{opts[:hashFormat][:type]}({width: 60}); formatter.format(data, #{opts[:hashFormat][:column]});"
    end

  @arrData = arrData
  @template = get_template
  @div = UUIDTools::UUID.random_create

end

Public Instance Methods

render() click to toggle source
# File lib/html_table.rb, line 32
def render
  unless @template.nil? || @arrData.nil?
    ERB.new(@template).result(binding)
  end
end
save(file) click to toggle source
# File lib/html_table.rb, line 38
def save(file)
  File.open(file, "w+") do |f|
    f.write(render)
  end
end

Private Instance Methods

build_json(arr) click to toggle source
# File lib/html_table.rb, line 76
def build_json(arr)

  arrData = Hash.new
  arrData['cols'] = Array.new

  arr.first.each_pair do |k,v|

    if v.to_s.numeric?
      type = 'number'
    else
      type = 'string'
    end

    hCol = Hash.new
    hCol['id'] = k
    hCol['label'] = k
    hCol['type'] = type
    arrData['cols'] <<  hCol

  end

  arrData['rows'] = Array.new

  arr.each do |r|

    hRow = Hash.new
    hRow[:c] = Array.new

    r.each_pair do |k,v|
      hCell = Hash.new
      hCell[:v] = v
      hRow[:c] << hCell
    end

    arrData['rows'] << hRow

  end

  return arrData.to_json

end
get_template() click to toggle source
# File lib/html_table.rb, line 46
def get_template()
  %{
    <head>
    <script type='text/javascript' src='https://www.google.com/jsapi'></script>
    <script type='text/javascript'>
      google.load('visualization', '1', {packages:['table']});
      google.setOnLoadCallback(drawTable);
      function drawTable() {

        var data = new google.visualization.DataTable(<%= @arrData %>);

        <%= @sort_code %>

        var table = new google.visualization.Table(document.getElementById('<%= @div %>'));

        <%= @format_code %>

        table.draw(data, {allowHtml: true, showRowNumber: true});
      }
    </script>
    </head>
    <body>
    <div id="<%= @div %>" style="width: 900px; height: 500px;"></div>
    </body>
}

end