Sha256: 06823d2f54f24b40bde9d8044a0d0e61ccc5892104f4ba3ff254bc72bf073bd3

Contents?: true

Size: 1.13 KB

Versions: 24

Compression:

Stored size: 1.13 KB

Contents

class Cl
  class Help
    class Table
      include Wrap

      attr_reader :data, :padding

      def initialize(data)
        @data = data
      end

      def any?
        data.any?
      end

      def format(padding = 8)
        @padding = padding
        rows.join("\n")
      end
      alias to_s format

      def rows
        data.map { |row| cells(row).join(' ').rstrip }
      end

      def cells(row)
        row.map.with_index do |cell, ix|
          indent(wrap(cell.to_s), widths[ix - 1]).ljust(widths[ix])
        end
      end

      def indent(str, width)
        return str if str.empty? || !width
        [str.lines[0], *str.lines[1..-1].map { |str| ' ' * (width + 1) + str }].join.rstrip
      end

      def width
        widths = cols[0..-2].map { |col| col.max_by(&:size).size }.inject(&:+).to_i
        widths + cols.size - 1
      end

      def widths
        cols.map.with_index do |col, ix|
          max = col.compact.max_by(&:size)
          width = max ? max.size : 0
          ix < cols.size - 2 ? width : width + padding.to_i
        end
      end

      def cols
        @cols ||= data.transpose
      end
    end
  end
end

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
cl-1.0.0 lib/cl/help/table.rb
cl-0.1.28 lib/cl/help/table.rb
cl-0.1.27 lib/cl/help/table.rb
cl-0.1.26 lib/cl/help/table.rb
cl-0.1.25 lib/cl/help/table.rb
cl-0.1.24 lib/cl/help/table.rb
cl-0.1.23 lib/cl/help/table.rb
cl-0.1.22 lib/cl/help/table.rb
cl-0.1.21 lib/cl/help/table.rb
cl-0.1.20 lib/cl/help/table.rb
cl-0.1.19 lib/cl/help/table.rb
cl-0.1.18 lib/cl/help/table.rb
cl-0.1.17 lib/cl/help/table.rb
cl-0.1.16 lib/cl/help/table.rb
cl-0.1.15 lib/cl/help/table.rb
cl-0.1.14 lib/cl/help/table.rb
cl-0.1.13 lib/cl/help/table.rb
cl-0.1.12 lib/cl/help/table.rb
cl-0.1.11 lib/cl/help/table.rb
cl-0.1.10 lib/cl/help/table.rb