Class: Jekyll::DatabaseTables::PsqlFormatter

Inherits:
Formatter
  • Object
show all
Includes:
Formatter::Helpers
Defined in:
lib/jekyll-database-tables/formatters.rb

Overview

Renders a Table as a psql-style terminal table inside a <pre> block.

Output uses space-padded columns separated by |, with a --+ divider between the header and data rows. Intended to evoke a database query result.

Examples:

puts PsqlFormatter.new.render(table)

<pre class="psql-table">
Name  | Age
------+----
Alice | 30
</pre>

Instance Method Summary collapse

Methods included from Formatter::Helpers

#column_widths

Instance Method Details

#format_row(cells, widths) ⇒ string

formats a row as space-padded cells joined by |.

Parameters:

  • cells (array<#to_s>)

    the cell values to render

  • widths (array<integer>)

    the column widths to left-justify against

Returns:

  • (string)

    the formatted row, with trailing whitespace stripped



97
98
99
100
101
# File 'lib/jekyll-database-tables/formatters.rb', line 97

def format_row(cells, widths)
  cells.each_with_index.map do |cell, i|
    CGI.escapeHTML(cell.to_s.ljust(widths[i]))
  end.join(' | ').rstrip
end

#render(table, title: nil) ⇒ String

Renders the table as a <pre class=“psql-table”> block.

Parameters:

  • table (Table)

    the table to render

  • title (String, nil) (defaults to: nil)

    an optional title, centered above the headers

Returns:

  • (String)

    the HTML <pre> block



82
83
84
85
86
87
88
89
90
# File 'lib/jekyll-database-tables/formatters.rb', line 82

def render(table, title: nil)
  widths = column_widths(table)

  <<~HTML
    <pre class="psql-table">
    #{table_rows(table, widths, title).join("\n")}
    </pre>
  HTML
end

#separator(widths) ⇒ string

renders a --+ separator sized to the given column widths.

Parameters:

  • widths (array<integer>)

    the column widths

Returns:

  • (string)

    the separator line



107
108
109
# File 'lib/jekyll-database-tables/formatters.rb', line 107

def separator(widths)
  widths.map { |w| '-' * w }.join('-+-')
end