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



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

def format_row(cells, widths)
  cells.each_with_index.map do |cell, i|
    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



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/jekyll-database-tables/formatters.rb', line 80

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

  lines = +''
  lines << "#{title.center(total_width(widths)).rstrip}\n" if title

  lines << format_row(table.headers, widths)
  lines << "\n"
  lines << separator(widths)
  lines << "\n"

  table.rows.each do |row|
    lines << format_row(row.cells, widths)
    lines << "\n"
  end

  "<pre class=\"psql-table\">\n#{lines}</pre>\n"
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



114
115
116
# File 'lib/jekyll-database-tables/formatters.rb', line 114

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