Class: Marktable::Formatters::HTML

Inherits:
Object
  • Object
show all
Defined in:
lib/marktable/formatters/html.rb

Class Method Summary collapse

Class Method Details

.format(rows, headers = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/marktable/formatters/html.rb', line 8

def self.format(rows, headers = nil)
  return '' if rows.empty? && headers.nil?

  builder = Nokogiri::HTML::Builder.new do |doc|
    doc.table do
      if headers
        doc.thead do
          doc.tr do
            headers.each do |header|
              doc.th { doc.text header }
            end
          end
        end
      end

      doc.tbody do
        rows.each do |row|
          doc.tr do
            row.values.each do |cell|
              doc.td do
                cell_text = cell.to_s
                if cell_text.include?('\n')
                  cell_text.split('\n').each_with_index do |line, index|
                    doc.br if index.positive?
                    doc.text line
                  end
                else
                  doc.text cell_text
                end
              end
            end
          end
        end
      end
    end
  end

  # Extract just the table element to avoid including DOCTYPE
  builder.doc.at_css('table').to_html
end