class PassStation::Output::Table
Simple table formatter
Public Class Methods
Format the +Array<CSV::Row>+ into a simple table with justified columns @param table [Array<CSV::Row>] an +Array<CSV::Row>+ @return [Array<String>] the formatted table ready to be printed
# File lib/pass_station/output.rb, line 74 def format(table) out = [] colsizes = colsizes_count(table) out.push(headers(colsizes)) table.each do |r| out.push(justify_row(r, colsizes)) end out end
Protected Class Methods
Calculate column size (max item size) @param table [Array<CSV::Row>] @param column [Symbol] the symbol of the column @return [Integer] the column size
# File lib/pass_station/output.rb, line 88 def colsize_count(table, column) table.map { |i| i[column].nil? ? 0 : i[column].size }.max + 1 end
Calculate the size of all columns (max item size) @param table [Array<CSV::Row>] @return [Hash] keys are columns name, values are columns size
# File lib/pass_station/output.rb, line 95 def colsizes_count(table) colsizes = table.first.to_h.keys.each_with_object({}) do |c, h| h[c] = colsize_count(table, c) end correct_min_colsizes(colsizes) end
Correct colsizes to be at least of the size of the headers (case when values are shorter than headers and breaks the table display) @param colsizes [Hash] hash containing the column size for each column as returned by {colsizes_count} @return [Hash] fixed colsizes, keys are columns name, values are columns size
# File lib/pass_station/output.rb, line 106 def correct_min_colsizes(colsizes) min_colsizes = { productvendor: 14, username: 9, password: 9 } min_colsizes.each_with_object({}) { |(k, v), h| h[k] = [v, colsizes[k]].max } end
Generate justified headers @param colsizes [Hash] hash containing the column size for each column as returned by {colsizes_count} @return [String] the justified headers
# File lib/pass_station/output.rb, line 139 def headers(colsizes) colsizes.map { |k, v| k.to_s.ljust(v) }.join.to_s end
Left justify an element of the column @param row [CSV::Row] CSV::Row
@param column [Symbol] the symbol of the column @param colsizes [Hash] hash containing the column size for each column as returned by {colsizes_count} @return [String] the justified element
# File lib/pass_station/output.rb, line 120 def justify(row, column, colsizes) row[column].to_s.ljust(colsizes[column]) end
Left justify all elements of the column @param row [CSV::Row] CSV::Row
@param colsizes [Hash] hash containing the column size for each column as returned by {colsizes_count} @return [String] the justified row
# File lib/pass_station/output.rb, line 128 def justify_row(row, colsizes) out = '' row.to_h.each_key do |col| out += justify(row, col, colsizes) end out end