Sha256: e7a32a1fe1dae36d458414592b40bfb8377fcfe9d582cfe9620ca0ae0cc33c76

Contents?: true

Size: 952 Bytes

Versions: 6

Compression:

Stored size: 952 Bytes

Contents

module WhoAmI
  class TextTable
    include Enumerable

    def initialize(join:, prefix: "", suffix: "")
      @join = join
      @prefix = prefix
      @suffix = suffix
      @rows = []
      @column_lengths = []
    end

    def push(row)
      @rows.push(row)

      row.each.with_index do |field, index|
        @column_lengths[index] =
          if @column_lengths[index].nil?
            field.length
          else
            [@column_lengths[index], field.length].max
          end
      end

      true
    end

    def each
      if !block_given?
        return enum_for(:each)
      end

      @rows.each do |row|
        output_fields =
          row.map.with_index do |field, index|
            field.to_s.ljust(@column_lengths[index], " ")
          end

        output_row = @prefix + output_fields.join(@join) + @suffix

        yield output_row
      end
    end

    def to_s
      map(&:rstrip).join("\n") + "\n"
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
who_am_i-0.0.6 lib/who_am_i/text_table.rb
who_am_i-0.0.5 lib/who_am_i/text_table.rb
who_am_i-0.0.4 lib/who_am_i/text_table.rb
who_am_i-0.0.3 lib/who_am_i/text_table.rb
who_am_i-0.0.2 lib/who_am_i/text_table.rb
who_am_i-0.0.1 lib/who_am_i/text_table.rb