class AlignedTable

Constants

VERSION

Attributes

rows[RW]
separator[RW]
title[RW]

Public Class Methods

new() click to toggle source
# File lib/aligned_table.rb, line 6
def initialize
  @separator = " "
end

Public Instance Methods

column_lengths() click to toggle source
# File lib/aligned_table.rb, line 25
def column_lengths
  columns = []

  @rows.each do |row|
    row.each_with_index do |col, index|
      columns[index] ||= []
      columns[index] << col
    end
  end

  columns.map! do |col|
    col.map { |x| x.to_s }.max_by(&:length).length
  end

  columns
end
render() click to toggle source
# File lib/aligned_table.rb, line 10
def render
  col_len = column_lengths
  rows = @rows.map do |row|
    render_row(row, col_len)
  end

  max_row_length = rows.max_by(&:length).length

  if @title
    rows.unshift(" #@title ".center(max_row_length, "="))
  end

  rows.join("\n")
end
render_row(row, col_len) click to toggle source
# File lib/aligned_table.rb, line 42
def render_row(row, col_len)
  columns = row.each_with_index.map do |col, index|
    if col.is_a?(Symbol)
      col.to_s * col_len[index]
    else
      if index == 0
        col.to_s.rjust(col_len[index])
      else
        col.to_s.ljust(col_len[index])
      end
    end
  end
  columns.join(@separator)
end