Sha256: 01651d76a8fc323bbf0ce0cdbf72710f31f34cbff8bef8d50577001370677ba7

Contents?: true

Size: 1.92 KB

Versions: 15

Compression:

Stored size: 1.92 KB

Contents

module Sequel
  module PrettyTable
    # Prints nice-looking plain-text tables via puts
    # 
    #   +--+-------+
    #   |id|name   |
    #   |--+-------|
    #   |1 |fasdfas|
    #   |2 |test   |
    #   +--+-------+
    def self.print(records, columns = nil) # records is an array of hashes
      columns ||= records.first.keys.sort_by{|x|x.to_s}
      sizes = column_sizes(records, columns)
      sep_line = separator_line(columns, sizes)

      puts sep_line
      puts header_line(columns, sizes)
      puts sep_line
      records.each {|r| puts data_line(columns, sizes, r)}
      puts sep_line
    end

    ### Private Module Methods ###

    # Hash of the maximum size of the value for each column 
    def self.column_sizes(records, columns) # :nodoc:
      sizes = Hash.new {0}
      columns.each do |c|
        s = c.to_s.size
        sizes[c.to_sym] = s if s > sizes[c.to_sym]
      end
      records.each do |r|
        columns.each do |c|
          s = r[c].to_s.size
          sizes[c.to_sym] = s if s > sizes[c.to_sym]
        end
      end
      sizes
    end
    
    # String for each data line
    def self.data_line(columns, sizes, record) # :nodoc:
      '|' << columns.map {|c| format_cell(sizes[c], record[c])}.join('|') << '|'
    end
    
    # Format the value so it takes up exactly size characters
    def self.format_cell(size, v) # :nodoc:
      case v
      when Bignum, Fixnum
        "%#{size}d" % v
      when Float
        "%#{size}g" % v
      else
        "%-#{size}s" % v.to_s
      end
    end
    
    # String for header line
    def self.header_line(columns, sizes) # :nodoc:
      '|' << columns.map {|c| "%-#{sizes[c]}s" % c.to_s}.join('|') << '|'
    end

    # String for separtor line
    def self.separator_line(columns, sizes) # :nodoc:
      '+' << columns.map {|c| '-' * sizes[c]}.join('+') << '+'
    end

    private_class_method :column_sizes, :data_line, :format_cell, :header_line, :separator_line
  end
end

Version data entries

15 entries across 15 versions & 3 rubygems

Version Path
colincasey-sequel-2.10.1 lib/sequel_core/pretty_table.rb
colincasey-sequel-2.10.2 lib/sequel_core/pretty_table.rb
colincasey-sequel-2.10.4 lib/sequel_core/pretty_table.rb
sequel-2.11.0 lib/sequel_core/pretty_table.rb
sequel-2.10.0 lib/sequel_core/pretty_table.rb
sequel-2.7.1 lib/sequel_core/pretty_table.rb
sequel-2.3.0 lib/sequel_core/pretty_table.rb
sequel-2.4.0 lib/sequel_core/pretty_table.rb
sequel-2.5.0 lib/sequel_core/pretty_table.rb
sequel-2.7.0 lib/sequel_core/pretty_table.rb
sequel-2.8.0 lib/sequel_core/pretty_table.rb
sequel-2.6.0 lib/sequel_core/pretty_table.rb
sequel-2.9.0 lib/sequel_core/pretty_table.rb
sequel_core-2.1.0 lib/sequel_core/pretty_table.rb
sequel_core-2.2.0 lib/sequel_core/pretty_table.rb