Sha256: e925f4faa45ef57fee08da248b47cf9250c9c501e3a919d27120b4ee9ea71d7b

Contents?: true

Size: 1.4 KB

Versions: 1

Compression:

Stored size: 1.4 KB

Contents

module Termtable
  class Render
    DEFAULT_PADDING = 1
    DEFAULT_ALIGNMENT = 'left'.freeze

    def initialize(rows, opts)
      @rows           = rows
      @padding        = opts.delete(:padding) || DEFAULT_PADDING
      @alignment      = opts.delete(:alignment) || DEFAULT_ALIGNMENT
      @border_options = opts.delete(:border)
      @column_lengths = column_widths(rows)
    end

    def set_metadata!
      @rows.each do |row|
        row.cells.each_with_index do |cell, idx|
          cell.max_column_size = @column_lengths[idx]
          cell.padding         = @padding
          cell.alignment       = @alignment
          cell.total_padding   = total_padding
        end
      end
    end

    def set_borders!
      @rows.unshift(Termtable::Border.new(columns: @column_lengths))
      @rows.push(Termtable::Border.new(columns: @column_lengths))
    end

    def set_headers_border!
      @rows.insert(2, Termtable::Border.new(columns: @column_lengths)) if @rows[1].is_a?(Termtable::Header)
    end

    def total_padding
      @alignment == 'center' ? @padding * 2 : @padding
    end

    def column_widths(rows)
      column_values = rows.map { |r| r.cells.map(&:value) }.transpose
      column_values.map do |col|
        col.max_by(&:length).size + total_padding
      end
    end

    def exec
      set_metadata!
      set_borders!
      set_headers_border!

      @rows.map(&:render).join("\n")
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
termtable-0.1.0 lib/termtable/render.rb