Sha256: e357880c0293b294c0714f0f85e0bff2e2638973298bfcbc22449e158323eb53

Contents?: true

Size: 1.58 KB

Versions: 4

Compression:

Stored size: 1.58 KB

Contents

module DaruLite
  module Formatters
    class Table
      def self.format(data, options = {})
        new(data, options[:headers], options[:row_headers])
          .format(options[:threshold], options[:spacing])
      end

      def initialize(data, headers, row_headers)
        @data = data || []
        @headers = (headers || []).to_a
        @row_headers = (row_headers || []).to_a
        @row_headers = [''] * @data.to_a.size if @row_headers.empty?
      end

      def format(threshold = nil, spacing = nil)
        rows = build_rows(threshold || DaruLite.max_rows)

        formatter = construct_formatter rows, spacing || DaruLite.spacing

        rows.map { |r| formatter % r }.join("\n")
      end

      private

      def build_rows(threshold)
        @row_headers.first(threshold).zip(@data).map do |(r, datarow)|
          [*[r].flatten.map(&:to_s), *(datarow || []).map { |v| pretty_to_s(v) }]
        end.tap do |rows|
          unless @headers.empty?
            spaces_to_add = rows.empty? ? 0 : rows.first.size - @headers.size
            rows.unshift ([''] * spaces_to_add) + @headers.map(&:to_s)
          end

          rows << (['...'] * rows.first.count) if @row_headers.count > threshold
        end
      end

      def construct_formatter(rows, spacing)
        width = rows.flatten.map(&:size).max || 0
        width = [3, width].max # not less than 'nil'
        width = [width, spacing].min # not more than max width

        " %#{width}.#{width}s" * rows.first.size if rows.first
      end

      def pretty_to_s(val)
        val.nil? ? 'nil' : val.to_s
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
daru_lite-0.1.3 lib/daru_lite/formatters/table.rb
daru_lite-0.1.2 lib/daru_lite/formatters/table.rb
daru_lite-0.1.1 lib/daru_lite/formatters/table.rb
daru_lite-0.1 lib/daru_lite/formatters/table.rb