Class: CucumberTable::Table

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

Instance Method Summary collapse

Constructor Details

#initialize(table) ⇒ Table

Returns a new instance of Table.



3
4
5
# File 'lib/table/table.rb', line 3

def initialize table
  @table = table
end

Instance Method Details

#[](column) ⇒ Object



23
24
25
26
# File 'lib/table/table.rb', line 23

def [] column
  index = headers.index column.to_s
  rows.map {|row| row[index]} if index
end

#each_colObject



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/table/table.rb', line 73

def each_col
  enum = Enumerator.new do |enum|
    headers.size.times do |i|
      enum << raw.map {|row| row[i] }
    end
  end

  if block_given?
    loop { yield enum.next }
    self
  else
    enum
  end
end

#each_row(&block) ⇒ Object



69
70
71
# File 'lib/table/table.rb', line 69

def each_row &block
  rows.each(&block)
end

#hashesObject



19
20
21
# File 'lib/table/table.rb', line 19

def hashes
  rows.map {|arr| arr.each_with_index.inject({}) {|h, (ele, i)| h[headers[i]] = ele; h }}
end

#headersObject



15
16
17
# File 'lib/table/table.rb', line 15

def headers
  @table.first
end

#map_column!(column, strict = true, &conversion_proc) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/table/table.rb', line 28

def map_column! column, strict = true, &conversion_proc
  index = headers.index column.to_s
  if index.nil?
    return unless strict
    raise 'column not found'
  end
  rows.each {|row| row[index] = conversion_proc[row[index]] } if conversion_proc
  self
end

#map_headers(mappings = {}, &block) ⇒ Object



50
51
52
53
# File 'lib/table/table.rb', line 50

def map_headers mappings = {}, &block
  clone = self.class.new [headers.dup, *rows]
  clone.map_headers! mappings, &block
end

#map_headers!(mappings = {}, &block) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/table/table.rb', line 38

def map_headers! mappings = {}, &block
  headers.each_with_index {|header, index|
    map = mappings.keys.select {|map| map === header }.first
    if map
      headers[index] = mappings[map]
    elsif block
      headers[index] = block[header]
    end
  }
  self
end

#rawObject



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

def raw
  @table
end

#rowsObject



7
8
9
# File 'lib/table/table.rb', line 7

def rows
  @table[1..-1]
end

#rows_hashObject



55
56
57
58
# File 'lib/table/table.rb', line 55

def rows_hash
  raise TableFormatException.new('The table must be exactly two columns wide') unless width == 2
  @table.inject({}) {|h, row| h[row[0]] = row[1]; h }
end

#transposeObject



64
65
66
67
# File 'lib/table/table.rb', line 64

def transpose
  new_table = headers.zip(*rows)
  self.class.new new_table
end

#widthObject



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

def width
  headers.size
end