Sha256: ee14bcedac740319275de958575e5134b2b2ef3a69e40181ecc3d2a55f1add03

Contents?: true

Size: 1.05 KB

Versions: 10

Compression:

Stored size: 1.05 KB

Contents

# encoding: UTF-8

require 'colored'

module Tms
  class Table
    attr_accessor :cols, :rows

    def initialize(&block)
      @cols, @rows = [], []
      yield self if block_given?
    end

    ADJUST = {:left => :ljust, :right => :rjust, :center => :center}
    def col(name, color = nil, adjust = nil)
      @cols << {:name => name, :color => color, :adjust => ADJUST[adjust]}
    end

    def <<(row)
      @rows << row
    end

    def lines
      @cols.each_with_index do |col, i|
        col[:width] = ([col[:name]] + @rows.map{ |row| row[i] }).map(&:to_s).map(&:length).max
      end

      ([@cols.map{ |col| col[:name] }] + @rows).each_with_index.map do |line, i|
        line.zip(@cols).map do |val, col|
          width, color, adjust = col.values_at(:width, :color, :adjust)
          adjust ||= val.is_a?(Integer) ? :rjust : :ljust
          val_s = val.to_s.send(adjust, width)
          val_s = Colored.colorize(val_s, :foreground => color) if color
          val_s
        end.join(' ')
      end
    end

    def print
      puts lines
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
tms-1.7.3 lib/tms/table.rb
tms-1.7.2 lib/tms/table.rb
tms-1.7.1 lib/tms/table.rb
tms-1.7.0 lib/tms/table.rb
tms-1.6.0 lib/tms/table.rb
tms-1.5.0 lib/tms/table.rb
tms-1.4.2 lib/tms/table.rb
tms-1.4.0 lib/tms/table.rb
tms-1.3.5 lib/tms/table.rb
tms-1.3.4 lib/tms/table.rb