class Terminal::Table

Constants

VERSION

Attributes

column_widths[RW]
headings[RW]
new_line_symbol[RW]
rows[RW]

Public Class Methods

new(object = nil, options = {}) { |self| ... } click to toggle source
# File lib/terminal/table.rb, line 77
def initialize(object = nil, options = {})
  @rows = []
  @headings = []
  @column_widths = []

  if options[:use_new_line_symbol]
    @new_line_symbol = '⏎'
  else
    @new_line_symbol = ' '
  end

  if object
    if object.is_a?(Hash)
      add_hash(object, options)
    elsif object.respond_to?(:each)
      object.each { |o| add_object(o, options) }
    else
      add_object(object, options)
    end
  end

  yield self if block_given?
  recalculate_column_widths!
end
special_tokens() click to toggle source
# File lib/terminal/table.rb, line 168
def special_tokens
  String::CHARS_OF_WIDTH_OF_1 + String::CHARS_OF_WIDTH_OF_0
end

Public Instance Methods

add_hash(hash, options) click to toggle source
# File lib/terminal/table.rb, line 110
def add_hash(hash, options)
  if options[:only]
    hash.keep_if { |k, v| options[:only].map(&:to_sym).include?(k) }
  elsif options[:except]
    hash.delete_if { |k, v| options[:except].map(&:to_sym).include?(k) }
  end

  @headings = hash.keys.map(&:to_s)
  @rows << hash.values
end
add_object(object, options) click to toggle source
# File lib/terminal/table.rb, line 102
def add_object(object, options)
  if object.respond_to?(:to_hash)
    add_hash(object.to_hash, options)
  elsif object.respond_to?(:each)
    @rows << object
  end
end
headings=(headings) click to toggle source
# File lib/terminal/table.rb, line 121
def headings=(headings)
  @headings = headings
end
recalculate_column_widths!() click to toggle source
# File lib/terminal/table.rb, line 125
def recalculate_column_widths!
  @rows = rows.map { |row| row.map { |item| item.to_s.gsub("\r\n", @new_line_symbol).gsub("\n", @new_line_symbol).gsub("\r", @new_line_symbol) } }

  if @rows.count > 0
    (0...@rows.first.size).each do |col|
      @column_widths[col] = @rows.map { |row| row[col].to_s.twidth }.max
    end
  end

  if @headings.count > 0
    (0...@headings.size).each do |col|
      @column_widths[col] = [@column_widths[col] || 0, @headings[col].twidth].max
    end
  end
end
to_s() click to toggle source
# File lib/terminal/table.rb, line 141
def to_s
  recalculate_column_widths!

  result = ''

  header_and_footer = '+' + @column_widths.map { |w| '-' * (w + 2) }.join('+') + '+' + "\n"

  if @headings.count > 0
    result += header_and_footer

    content = @headings.each_with_index.map { |grid, i| grid.to_s.tljust(@column_widths[i]) }

    result += '| ' + content.join(' | ') + " |\n"
  end

  result += header_and_footer

  @rows.each do |row|
    content = row.each_with_index.map { |grid, i| grid.to_s.tljust(@column_widths[i]) }

    result += '| ' + content.join(' | ') + " |\n"
  end

  result + header_and_footer
end