Class: Tablizer::Table

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/tablizer/table.rb

Constant Summary collapse

DEFAULTS =
{
  align: 'ansi_ljust',
  header: false,
  footer: false
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content = [], params = {}) ⇒ Table

Returns a new instance of Table.



20
21
22
23
24
25
26
# File 'lib/tablizer/table.rb', line 20

def initialize(content = [], params = {})
  @options = DEFAULTS.merge(params)

  raise "Cannot set rows and columns at the same time." if @options.has_key?(:cols) && @options.has_key?(:rows)

  set_content content
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



12
13
14
# File 'lib/tablizer/table.rb', line 12

def content
  @content
end

#optionsObject

Returns the value of attribute options.



12
13
14
# File 'lib/tablizer/table.rb', line 12

def options
  @options
end

Instance Method Details

#<=>(other) ⇒ Object



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

def <=>(other)
  size <=> other
end

#[](col, row) ⇒ Object



39
40
41
# File 'lib/tablizer/table.rb', line 39

def [](col, row)
  @content[row][col].to_s
end

#[]=(col, row, value) ⇒ Object

The []= method let’s you access the Table object data as if it was a 2 dimension Array. You can call []= in the form ‘obj = value’, or, in mathematical terms, ‘obj = value’



34
35
36
37
# File 'lib/tablizer/table.rb', line 34

def []=(col, row, value)
  @content[row] ||= []
  @content[row][col] = value
end

#columnsObject



79
80
81
# File 'lib/tablizer/table.rb', line 79

def columns
  @content.collect { |a| a.length }.max || 0
end

#each(&block) ⇒ Object



48
49
50
# File 'lib/tablizer/table.rb', line 48

def each(&block)
  block_given? ? enumerator.each(&block) : enumerator
end

#empty?Boolean

Returns:

  • (Boolean)


43
44
45
46
# File 'lib/tablizer/table.rb', line 43

def empty?
  each { |elem| return false if elem =~ /\S/ }
  true
end

#enumeratorObject



52
53
54
55
56
57
58
59
60
61
# File 'lib/tablizer/table.rb', line 52

def enumerator
  Enumerator.new do |yielder|
    number_of_columns, number_of_rows = columns, rows
    (0...number_of_rows).each do |row_index|
      (0...number_of_columns).each do |column_index|
        yielder.yield self[column_index, row_index]
      end
    end
  end
end

#rowsObject



83
84
85
# File 'lib/tablizer/table.rb', line 83

def rows
  @content.length
end

#set_content(content) ⇒ Object



28
29
30
# File 'lib/tablizer/table.rb', line 28

def set_content(content)
  @content = content.dup
end

#sizeObject



67
68
69
# File 'lib/tablizer/table.rb', line 67

def size
  rows * columns
end

#to_sObject



71
72
73
# File 'lib/tablizer/table.rb', line 71

def to_s
  tablize
end

#to_s_with_marginsObject



75
76
77
# File 'lib/tablizer/table.rb', line 75

def to_s_with_margins
  ("\n" * 4) << to_s << ("\n" * 4)
end