Sha256: fdb41c1651f7d3a2ae66f907a33e9e627c1945fd683d2d247940d52a2efa7283

Contents?: true

Size: 1.07 KB

Versions: 18

Compression:

Stored size: 1.07 KB

Contents

class Ppl::Format::Table

  SEPARATOR_SPACES = 0
  SEPARATOR_TABS   = 1

  attr_accessor :columns
  attr_accessor :rows
  attr_accessor :separator

  def initialize(columns=[])
    @columns   = columns
    @rows      = []
    @separator = SEPARATOR_SPACES

    @column_widths = {}
    @columns.each { |c| @column_widths[c] = 0 }
  end

  def add_row(row={})
    row.each do |column, value|
      width     = sprintf("%s", value).length
      max_width = @column_widths[column]
      if width > max_width
        @column_widths[column] = width
      end
    end
    @rows.push(row)
  end

  def to_s
    string = ""
    @rows.each { |row| string += format_row(row).strip + "\n" }
    string.strip
  end


  private

  def format_row(row)
    string = ""
    @columns.each { |column| string += format_cell(row, column) }
    return string
  end

  def format_cell(row, column)
    width  = @column_widths[column]
    if @separator == SEPARATOR_SPACES
      string = sprintf("%-#{width}s  ", row[column])
    else
      string = sprintf("%s\t", row[column])
    end
    return string
  end

end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
ppl-1.14.1 lib/ppl/format/table.rb
ppl-1.14.0 lib/ppl/format/table.rb
ppl-1.13.0 lib/ppl/format/table.rb
ppl-1.12.0 lib/ppl/format/table.rb
ppl-1.11.0 lib/ppl/format/table.rb
ppl-1.10.0 lib/ppl/format/table.rb
ppl-1.9.0 lib/ppl/format/table.rb
ppl-1.8.0 lib/ppl/format/table.rb
ppl-1.7.0 lib/ppl/format/table.rb
ppl-1.6.0 lib/ppl/format/table.rb
ppl-1.5.3 lib/ppl/format/table.rb
ppl-1.5.2 lib/ppl/format/table.rb
ppl-1.5.1 lib/ppl/format/table.rb
ppl-1.5.0 lib/ppl/format/table.rb
ppl-1.4.1 lib/ppl/format/table.rb
ppl-1.3.0 lib/ppl/format/table.rb
ppl-1.2.0 lib/ppl/format/table.rb
ppl-1.1.0 lib/ppl/format/table.rb