Sha256: 3ead3b516f65187867bc1896a96622deca55ad0628e9a0ba3b324553c0992e5e

Contents?: true

Size: 1.1 KB

Versions: 3

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

class HtmlFormatter
  attr_reader :indent

  def initialize(table)
    @table = table
    @indent = '    '
  end

  def to_html
    @lines = []
    @lines << '<table>'
    append_table_head
    append_table_body
    @lines << '</table>'
    @lines.join("\n") + "\n"
  end

  private

  def append_table_head
    @lines << "#{indent}<thead>"
    unless @table.empty?
      rows = @table.text_table.rows[0..0]
      append_rows(rows, 'th')
    end
    @lines << "#{indent}</thead>"
  end

  def append_table_body
    @lines << "#{indent}<tbody>"
    unless @table.empty?
      rows = @table.text_table.rows[2..-1]
      append_rows(rows, 'td')
    end
    @lines << "#{indent}</tbody>"
  end

  def append_rows(rows, tag)
    rows.each do |row|
      next if row == :separator

      @lines << "#{indent}<tr>"
      row.map do |cell|
        value = cell_value(cell)
        @lines << "#{indent}#{indent}<#{tag}>#{value}</#{tag}>"
      end
      @lines << "#{indent}</tr>"
    end
  end

  def cell_value(cell)
    case cell
    when Hash
      cell[:value]
    else
      cell
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tablesmith-0.6.2 lib/tablesmith/html_formatter.rb
tablesmith-0.6.0 lib/tablesmith/html_formatter.rb
tablesmith-0.5.0 lib/tablesmith/html_formatter.rb