Sha256: da110ad2defebf0443101c4fbc9784626a6211659036675103302112965d93b1

Contents?: true

Size: 1.98 KB

Versions: 5

Compression:

Stored size: 1.98 KB

Contents

module ObjectTable::Printable

  def self.get_printable_column(name, column)
    padding = [nil] * (column.rank - 1)
    rows = column.shape[-1].times.map do |i|
      row = column[*padding, i]
      str = row.is_a?(NArray) ? row.inspect.partition("\n")[-1].strip : row.inspect
      str.split("\n")
    end

    name = name.to_s
    [[name]] + rows + [[name]]
  end

  def self.get_printable_line_numbers(numbers)
    rows = numbers.map do |i|
      ["#{i}: "]
    end

    [['']] + rows + [['']]
  end

  def inspect(max_section = 5, col_padding = 2)
    header = "#{self.class}(#{nrows}, #{ncols})\n"

    return (header + "(empty table)") if ncols == 0
    return (header + "(empty table with columns: #{colnames.join(", ")})") if nrows == 0

    printed_columns = []

    if nrows > max_section * 2
      head = (0...max_section)
      tail = ((nrows - max_section)...nrows)

      printed_columns.push ObjectTable::Printable.get_printable_line_numbers(head.to_a + tail.to_a)

      printed_columns += columns.map do |name, c|
        padding = [nil] * (c.rank - 1)
        c = c.slice(*padding, [head, tail])
        ObjectTable::Printable.get_printable_column(name, c)
      end
    else
      max_section = -1
      printed_columns.push ObjectTable::Printable.get_printable_line_numbers(0...nrows)
      printed_columns += columns.map do |name, c|
        ObjectTable::Printable.get_printable_column(name, c)
      end
    end

    widths = printed_columns.map{|row| row.flat_map{|c| c.map(&:length)}.max + col_padding}

    header + printed_columns.transpose.each_with_index.map do |row, index|
      height = row.map(&:length).max

      row = row.zip(widths).map do |cell, width|
        cell += [" "] * (height - cell.length)
        cell.map{|i| i.rjust(width)}
      end

      row = row.transpose.map{|i| i.join('')}.join("\n")

      if index == max_section
        row += "\n" + '-'*widths.reduce(:+)
      end
      row
    end.join("\n")

  rescue NoMethodError => e
    raise Exception.new(e)
  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
object_table-0.3.0 lib/object_table/printable.rb
object_table-0.2.8 lib/object_table/printable.rb
object_table-0.2.4 lib/object_table/printable.rb
object_table-0.2.3 lib/object_table/printable.rb
object_table-0.2.2 lib/object_table/printable.rb