Module: Moult::Formatters::TextTable

Defined in:
lib/moult/formatters/text_table.rb

Overview

Shared plumbing for the header + rows text tables every analysis formatter renders. Extracted so the column-width/alignment logic lives in exactly one place instead of being copied into each *_table formatter (the gate caught that duplication when run on Moult itself).

Columns left-align by default; pass the 0-based indices to right-align (e.g. numeric columns) in right_aligned.

Constant Summary collapse

GUTTER =
"  "

Class Method Summary collapse

Class Method Details

.column_widths(headers, rows) ⇒ Object



26
27
28
29
30
# File 'lib/moult/formatters/text_table.rb', line 26

def column_widths(headers, rows)
  headers.each_index.map do |col|
    ([headers[col]] + rows.map { |r| r[col] }).map(&:length).max
  end
end

.format_row(cells, widths, right_aligned) ⇒ Object



32
33
34
35
36
# File 'lib/moult/formatters/text_table.rb', line 32

def format_row(cells, widths, right_aligned)
  cells.each_with_index.map { |cell, col|
    right_aligned.include?(col) ? cell.rjust(widths[col]) : cell.ljust(widths[col])
  }.join(GUTTER).rstrip
end

.render(headers, rows, right_aligned: []) ⇒ String

Returns the header row followed by each data row, newline-joined.

Parameters:

  • headers (Array<String>)
  • rows (Array<Array<String>>)
  • right_aligned (Array<Integer>) (defaults to: [])

    0-based column indices to right-align

Returns:

  • (String)

    the header row followed by each data row, newline-joined



21
22
23
24
# File 'lib/moult/formatters/text_table.rb', line 21

def render(headers, rows, right_aligned: [])
  widths = column_widths(headers, rows)
  ([headers] + rows).map { |cells| format_row(cells, widths, right_aligned) }.join("\n")
end