class MGit::Output::TableOutputter

Attributes

options[R]
table[R]

Public Class Methods

new(table, options) click to toggle source
# File lib/mgit/output.rb, line 36
def initialize(table, options)
  @table = table
  @options = options
  @options[:columns] = []
  fail ImplementationError, 'ptable called with invalid table' unless valid_table?
end

Public Instance Methods

to_s() click to toggle source
# File lib/mgit/output.rb, line 43
def to_s
  return '' if table.empty?

  cw = column_widths

  table.map do |row|
    row.map.with_index do |cell, i|
      # Only justify the column if it is not the last one.
      # This avoids too many line breaks.
      i < (columns - 1) ? justify(cell, cw[i]) : cell
    end.join(' | ')
  end.join("\n")
end

Private Instance Methods

column(nth) click to toggle source
# File lib/mgit/output.rb, line 67
def column(nth)
  table.map { |c| c[nth] }
end
column_max_widths() click to toggle source
# File lib/mgit/output.rb, line 81
def column_max_widths
  transpose.map do |col|
    col.map { |cell| cell.size }.max
  end
end
column_widths() click to toggle source
# File lib/mgit/output.rb, line 75
def column_widths
  column_max_widths.each_with_index.map do |c, i|
    (options[:columns].size > i && options[:columns][i]) ? options[:columns][i] : c
  end
end
columns() click to toggle source
# File lib/mgit/output.rb, line 63
def columns
  table.first.size
end
justify(s, n) click to toggle source
# File lib/mgit/output.rb, line 87
def justify(s, n)
  (s.size > n) ? (s[0..(n - 3)] + '...') : s.ljust(n, ' ')
end
transpose() click to toggle source
# File lib/mgit/output.rb, line 71
def transpose
  (0..(columns - 1)).map { |i| column(i) }
end
valid_table?() click to toggle source
# File lib/mgit/output.rb, line 59
def valid_table?
  table.empty? || table.all? { |c| c.is_a?(Array) && c.size == table.first.size }
end