Sha256: d066a080c3c23a6c7b26f0b3490651ef196c4ac6ec1bf50325769db14fb7c433

Contents?: true

Size: 1.16 KB

Versions: 4

Compression:

Stored size: 1.16 KB

Contents

class Formatador

  def display_table(hashes, keys = nil, &block)
    headers = keys || []
    widths = {}
    for hash in hashes
      for key in hash.keys
        unless keys
          headers << key
        end
        widths[key] = [key.to_s.length, widths[key] || 0, hash[key] && hash[key].to_s.length || 0].max
      end
      headers = headers.uniq
    end

    if block_given?
      headers = headers.sort(&block)
    elsif !keys
      headers = headers.sort {|x,y| x.to_s <=> y.to_s}
    end

    split = "+"
    if headers.empty?
      split << '--+'
    else
      for header in headers
        split << ('-' * (widths[header] + 2)) << '+'
      end
    end

    display_line(split)
    columns = []
    for header in headers
      columns << "#{header}#{' ' * (widths[header] - header.to_s.length)}"
    end
    display_line("| #{columns.join(' | ')} |")
    display_line(split)

    for hash in hashes
      columns = []
      for header in headers
        datum = hash[header] || ''
        columns << "#{datum}#{' ' * (widths[header] - datum.to_s.length)}"
      end
      display_line("| #{columns.join(' | ')} |")
      display_line(split)
    end
    nil
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
formatador-0.0.14 lib/formatador/table.rb
formatador-0.0.13 lib/formatador/table.rb
formatador-0.0.12 lib/formatador/table.rb
formatador-0.0.11 lib/formatador/table.rb