Class: ODDB::Text::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/oddb/text/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTable

Returns a new instance of Table.



10
11
12
13
# File 'lib/oddb/text/table.rb', line 10

def initialize
  @rows = [[]]
  next_cell!
end

Instance Attribute Details

#rowsObject (readonly)

Returns the value of attribute rows.



9
10
11
# File 'lib/oddb/text/table.rb', line 9

def rows
  @rows
end

Instance Method Details

#<<(str) ⇒ Object



63
64
65
# File 'lib/oddb/text/table.rb', line 63

def <<(str)
  @rows.last.last << str
end

#clean!Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/oddb/text/table.rb', line 14

def clean!
  @rows.each { |row|
    while((cell = row.last) && cell.empty?)
      row.pop
    end
  }
  while((row = @rows.last) && row.empty?)
    @rows.pop
  end
end

#column_widthsObject



24
25
26
27
28
29
30
31
# File 'lib/oddb/text/table.rb', line 24

def column_widths
  @rows.inject([]) { |memo, row|
    row.each_with_index { |cell, idx|
      memo[idx] = [memo[idx].to_i, cell.length].max
    }
    memo
  }
end

#each_normalized(&block) ⇒ Object



44
45
46
47
48
49
# File 'lib/oddb/text/table.rb', line 44

def each_normalized(&block)
  wd = width
  @rows.each { |row|
    block.call(row + Array.new(wd - row.length))
  }
end

#empty?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/oddb/text/table.rb', line 32

def empty?
  @rows.flatten.all? { |cell| cell.strip.empty? }
end

#next_cell!Object



35
36
37
38
39
# File 'lib/oddb/text/table.rb', line 35

def next_cell!
  cell = Paragraph.new
  @rows.last.push cell
  cell
end

#next_row!Object



40
41
42
43
# File 'lib/oddb/text/table.rb', line 40

def next_row!
  @rows.push []
  next_cell!
end

#to_sObject



50
51
52
53
54
55
56
57
58
59
# File 'lib/oddb/text/table.rb', line 50

def to_s
  widths = column_widths
  @rows.collect { |row|
    line = ''
    row.each_with_index { |cell, idx|
      line << cell.to_s.ljust(widths.at(idx) + 2)
    }
    line
  }.join("\n")
end

#widthObject



60
61
62
# File 'lib/oddb/text/table.rb', line 60

def width
  @rows.collect { |row| row.length }.max  
end