Class: TypedPrint::Table
- Inherits:
-
Object
- Object
- TypedPrint::Table
- Defined in:
- lib/typed_print/table.rb
Instance Method Summary collapse
-
#initialize(data, alignments = {}, only_columns = nil, custom_headers = {}) ⇒ Table
constructor
A new instance of Table.
- #render ⇒ Object
Constructor Details
#initialize(data, alignments = {}, only_columns = nil, custom_headers = {}) ⇒ Table
Returns a new instance of Table.
5 6 7 8 9 10 11 12 |
# File 'lib/typed_print/table.rb', line 5 def initialize(data, alignments = {}, only_columns = nil, custom_headers = {}) @data = data @alignments = alignments @only_columns = only_columns&.map(&:to_sym) @custom_headers = custom_headers.transform_keys(&:to_sym) @headers = determine_headers end |
Instance Method Details
#render ⇒ Object
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/typed_print/table.rb', line 14 def render return "" if @data.empty? # Build rows rows = @data.map { |row| @headers.map { |h| format_value(row[h]) } } # Build header strings (with custom headers or capitalized defaults) header_strings = @headers.map do |h| if @custom_headers[h] @custom_headers[h] else # Capitalize each word in the header h.to_s.split('_').map(&:capitalize).join(' ') end end # Calculate column widths column_widths = header_strings.map(&:length) rows.each do |row| row.each_with_index do |cell, i| column_widths[i] = [column_widths[i], cell.length].max end end # Build output output = [] output << format_row(header_strings, column_widths, :center) output << separator(column_widths) rows.each do |row| output << format_row(row, column_widths) end output.join("\n") end |