Sha256: 01edcd8bc279571a3614675b4657d6eccfdca5482714a6f6319b75e668a2340f

Contents?: true

Size: 1.32 KB

Versions: 4

Compression:

Stored size: 1.32 KB

Contents

# http://www.panic.com/statusboard/docs/table_tutorial.pdf
require 'csv'

module PanicBoardData

  class Table

    attr_accessor :data, :widths

    def initialize(data = [])
      @data = data
    end

    def to_html
      "<table>#{data_to_table_rows}</table>"
    end

    def to_csv
      self.class.to_csv self.data
    end

    def self.to_csv data
      ::CSV.generate do |csv|
        data.each { |row| csv << row }
      end.strip
    end

    private

    def data_to_table_rows
      return '' unless data
      data.map { |r| build_row_for r }.join
    end

    def build_row_for record
      result = record.each_with_index.map { |v, i| build_cell_for v, i }.join
      "<tr>#{result}</tr>"
    end

    def build_cell_for value, index
      value = flatten_a_value_array_to_a_single_value(value).to_s
      width = get_width_for index
      render_cell value, width
    end

    def flatten_a_value_array_to_a_single_value value
      value.is_a?(Array) ? value.join('') : value
    end

    def get_width_for index
      widths ? widths[index] : nil
    end

    def render_cell value, width
      return value if this_value_defines_a_td value
      width ? "<td style=\"width: #{width}px\">#{value}</td>"
            : "<td>#{value}</td>"
    end

    def this_value_defines_a_td value
      value[0..2] == '<td'
    end

  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
panic_board_data-1.0.2 lib/panic_board_data/table.rb
panic_board_data-1.0.1 lib/panic_board_data/table.rb
panic_board_data-1.0.0 lib/panic_board_data/table.rb
panic_board_data-0.0.12 lib/panic_board_data/table.rb