Module: ObjectTable::Printable

Included in:
TableMethods
Defined in:
lib/object_table/printable.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.get_printable_column(name, column) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/object_table/printable.rb', line 3

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

.get_printable_line_numbers(numbers) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/object_table/printable.rb', line 15

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

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

Instance Method Details

#inspect(max_section = 5, col_padding = 2) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/object_table/printable.rb', line 23

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