Class: Cucumber::Ast::Table

Inherits:
Object show all
Includes:
Enumerable
Defined in:
lib/cucumber/ast/table.rb

Overview

Holds the data of a table parsed from a feature file:

| a | b |
| c | d |

This gets parsed into a Table holding the values [['a', 'b'], ['c', 'd']]

Direct Known Subclasses

OutlineTable

Defined Under Namespace

Classes: Cell, Cells, SurplusCell

Constant Summary collapse

NULL_CONVERSIONS =
Hash.new(lambda{ |cell_value| cell_value }).freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw, conversion_procs = NULL_CONVERSIONS.dup) ⇒ Table

Returns a new instance of Table.



21
22
23
24
25
26
27
28
29
# File 'lib/cucumber/ast/table.rb', line 21

def initialize(raw, conversion_procs = NULL_CONVERSIONS.dup)
  @cells_class = Cells
  @cell_class = Cell

  # Verify that it's square
  transposed = raw.transpose
  create_cell_matrix(raw)
  @conversion_procs = conversion_procs
end

Instance Attribute Details

#fileObject

Returns the value of attribute file.



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

def file
  @file
end

Class Method Details

.default_arg_nameObject



17
18
19
# File 'lib/cucumber/ast/table.rb', line 17

def self.default_arg_name
  "table"
end

Instance Method Details

#accept(visitor) ⇒ Object



116
117
118
119
120
121
122
# File 'lib/cucumber/ast/table.rb', line 116

def accept(visitor)
  return if $cucumber_interrupted
  cells_rows.each do |row|
    visitor.visit_table_row(row)
  end
  nil
end

#arguments_replaced(arguments) ⇒ Object

:nodoc:



307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/cucumber/ast/table.rb', line 307

def arguments_replaced(arguments) #:nodoc:
  raw_with_replaced_args = raw.map do |row|
    row.map do |cell|
      cell_with_replaced_args = cell
      arguments.each do |name, value|
        if cell_with_replaced_args && cell_with_replaced_args.include?(name)
          cell_with_replaced_args = value ? cell_with_replaced_args.gsub(name, value) : nil
        end
      end
      cell_with_replaced_args
    end
  end
  Table.new(raw_with_replaced_args)
end

#cell_matrixObject



340
341
342
# File 'lib/cucumber/ast/table.rb', line 340

def cell_matrix
  @cell_matrix
end

#cells_rowsObject



326
327
328
329
330
# File 'lib/cucumber/ast/table.rb', line 326

def cells_rows
  @rows ||= cell_matrix.map do |cell_row|
    @cells_class.new(self, cell_row)
  end
end

#col_width(col) ⇒ Object



344
345
346
# File 'lib/cucumber/ast/table.rb', line 344

def col_width(col)
  columns[col].__send__(:width)
end

#diff!(other_table, options = {}) ⇒ Object

Compares other_table to self. If other_table contains columns and/or rows that are not in self, new columns/rows are added at the relevant positions, marking the cells in those rows/columns as surplus. Likewise, if other_table lacks columns and/or rows that are present in self, these are marked as missing.

surplus and missing cells are recognised by formatters and displayed so that it’s easy to read the differences.

Cells that are different, but look identical (for example the boolean true and the string “true”) are converted to their Object#inspect representation and preceded with (i) - to make it easier to identify where the difference actually is.

Since all tables that are passed to StepDefinitions always have String objects in their cells, you may want to use #map_column! before calling #diff!. You can use #map_column! on either of the tables.

An exception is raised if there are missing rows or columns, or surplus rows. An error is not raised for surplus columns. Whether to raise or not raise can be changed by setting values in options to true or false:

* <tt>missing_row</tt>: Raise on missing rows (defaults to true)
* <tt>surplus_row</tt>: Raise on surplus rows (defaults to true)
* <tt>missing_col</tt>: Raise on missing columns (defaults to true)
* <tt>surplus_col</tt>: Raise on surplus columns (defaults to false)

The other_table argument can be another Table, an Array of Array or an Array of Hash (similar to the structure returned by #hashes).

Calling this method is particularly useful in Then steps that take a Table argument, if you want to compare that table to some actual values.



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/cucumber/ast/table.rb', line 218

def diff!(other_table, options={})
  options = {:missing_row => true, :surplus_row => true, :missing_col => true, :surplus_col => false}.merge(options)

  other_table = ensure_table(other_table)
  other_table.convert_columns!
  ensure_green!

  original_width = cell_matrix[0].length
  other_table_cell_matrix = pad!(other_table.cell_matrix)
  padded_width = cell_matrix[0].length

  missing_col = cell_matrix[0].detect{|cell| cell.status == :undefined}
  surplus_col = padded_width > original_width

  require_diff_lcs
  cell_matrix.extend(Diff::LCS)
  convert_columns!
  changes = cell_matrix.diff(other_table_cell_matrix).flatten

  inserted = 0
  missing  = 0

  row_indices = Array.new(other_table_cell_matrix.length) {|n| n}

  last_change = nil
  missing_row_pos = nil
  insert_row_pos  = nil
  
  changes.each do |change|
    if(change.action == '-')
      missing_row_pos = change.position + inserted
      cell_matrix[missing_row_pos].each{|cell| cell.status = :undefined}
      row_indices.insert(missing_row_pos, nil)
      missing += 1
    else # '+'
      insert_row_pos = change.position + missing
      inserted_row = change.element
      inserted_row.each{|cell| cell.status = :comment}
      cell_matrix.insert(insert_row_pos, inserted_row)
      row_indices[insert_row_pos] = nil
      inspect_rows(cell_matrix[missing_row_pos], inserted_row) if last_change && last_change.action == '-'
      inserted += 1
    end
    last_change = change
  end

  other_table_cell_matrix.each_with_index do |other_row, i|
    row_index = row_indices.index(i)
    row = cell_matrix[row_index] if row_index
    if row
      (original_width..padded_width).each do |col_index|
        surplus_cell = other_row[col_index]
        row[col_index].value = surplus_cell.value if row[col_index]
      end
    end
  end
  
  clear_cache!
  should_raise = 
    missing_row_pos && options[:missing_row] ||
    insert_row_pos  && options[:surplus_row] ||
    missing_col     && options[:missing_col] ||
    surplus_col     && options[:surplus_col]
  raise 'Tables were not identical' if should_raise
end

#dupObject

Creates a copy of this table, inheriting the column mappings.



32
33
34
# File 'lib/cucumber/ast/table.rb', line 32

def dup
  self.class.new(raw.dup, @conversion_procs.dup)
end

#each_cells_row(&proc) ⇒ Object



112
113
114
# File 'lib/cucumber/ast/table.rb', line 112

def each_cells_row(&proc)
  cells_rows.each(&proc)
end

#has_text?(text) ⇒ Boolean

Returns:

  • (Boolean)


322
323
324
# File 'lib/cucumber/ast/table.rb', line 322

def has_text?(text)
  raw.flatten.compact.detect{|cell_value| cell_value.index(text)}
end

#hashesObject

Converts this table into an Array of Hash where the keys of each Hash are the headers in the table. For example, a Table built from the following plain text:

| a | b | sum |
| 2 | 3 | 5   |
| 7 | 9 | 16  |

Gets converted into the following:

[{'a' => '2', 'b' => '3', 'sum' => '5'}, {'a' => '7', 'b' => '9', 'sum' => '16'}]

Use #map_column! to specify how values in a column are converted.



65
66
67
68
69
# File 'lib/cucumber/ast/table.rb', line 65

def hashes
  @hashes ||= cells_rows[1..-1].map do |row|
    row.to_hash
  end.freeze
end

#header_cell(col) ⇒ Object



336
337
338
# File 'lib/cucumber/ast/table.rb', line 336

def header_cell(col)
  cells_rows[0][col]
end

#headersObject



332
333
334
# File 'lib/cucumber/ast/table.rb', line 332

def headers
  raw.first
end

#index(cells) ⇒ Object

:nodoc:



295
296
297
# File 'lib/cucumber/ast/table.rb', line 295

def index(cells) #:nodoc:
  cells_rows.index(cells)
end

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

Change how #hashes converts column values. The column_name argument identifies the column and conversion_proc performs the conversion for each cell in that column. If strict is true, an error will be raised if the column named column_name is not found. If strict is false, no error will be raised. Example:

Given /^an expense report for (.*) with the following posts:$/ do |table|
  posts_table.map_column!('amount') { |a| a.to_i }
  posts_table.hashes.each do |post|
    # post['amount'] is a Fixnum, rather than a String
  end
end


179
180
181
182
# File 'lib/cucumber/ast/table.rb', line 179

def map_column!(column_name, strict=true, &conversion_proc)
  verify_column(column_name) if strict
  @conversion_procs[column_name] = conversion_proc
end

#map_headers(mappings) ⇒ Object

Returns a new Table where the headers are redefined. See #map_headers!



161
162
163
164
165
# File 'lib/cucumber/ast/table.rb', line 161

def map_headers(mappings)
  table = self.dup
  table.map_headers!(mappings)
  table
end

#map_headers!(mappings) ⇒ Object

Redefines the table headers. This makes it possible to use prettier and more flexible header names in the features. The keys of mappings are Strings or regular expressions (anything that responds to #=== will work) that may match column headings in the table. The values of mappings are desired names for the columns.

Example:

| Phone Number | Address |
| 123456       | xyz     |
| 345678       | abc     |

A StepDefinition receiving this table can then map the columns with both Regexp and String:

table.map_headers!(/phone( number)?/i => :phone, 'Address' => :address)
table.hashes
# => [{:phone => '123456', :address => 'xyz'}, {:phone => '345678', :address => 'abc'}]


149
150
151
152
153
154
155
156
157
158
# File 'lib/cucumber/ast/table.rb', line 149

def map_headers!(mappings)
  header_cells = cell_matrix[0]
  mappings.each_pair do |pre, post|
    header_cell = header_cells.detect{|cell| pre === cell.value}
    header_cell.value = post
    if @conversion_procs.has_key?(pre)
      @conversion_procs[post] = @conversion_procs.delete(pre)
    end
  end
end

#rawObject

Gets the raw data of this table. For example, a Table built from the following plain text:

| a | b |
| c | d |

gets converted into the following:

[['a', 'b], ['c', 'd']]


99
100
101
102
103
104
105
# File 'lib/cucumber/ast/table.rb', line 99

def raw
  cell_matrix.map do |row|
    row.map do |cell|
      cell.value
    end
  end
end

#rowsObject

Same as #raw, but skips the first (header) row



108
109
110
# File 'lib/cucumber/ast/table.rb', line 108

def rows
  raw[1..-1]
end

#rows_hashObject

Converts this table into a Hash where the first column is used as keys and the second column is used as values

| a | 2 |
| b | 3 |

Gets converted into the following:

{'a' => '2', 'b' => '3'}

The table must be exactly two columns wide



83
84
85
86
87
# File 'lib/cucumber/ast/table.rb', line 83

def rows_hash
  return @rows_hash if @rows_hash
  verify_table_width(2)
  @rows_hash = self.transpose.hashes[0].freeze
end

#to_hash(cells) ⇒ Object

:nodoc:



284
285
286
287
288
289
290
291
292
293
# File 'lib/cucumber/ast/table.rb', line 284

def to_hash(cells) #:nodoc:
  hash = Hash.new do |hash, key|
    hash[key.to_s] if key.is_a?(Symbol)
  end
  raw[0].each_with_index do |column_name, column_index|
    value = @conversion_procs[column_name].call(cells.value(column_index))
    hash[column_name] = value
  end
  hash
end

#to_s(options = {}) ⇒ Object



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/cucumber/ast/table.rb', line 348

def to_s(options = {})
  options = {:color => true, :indent => 2, :prefixes => TO_S_PREFIXES}.merge(options)
  io = StringIO.new

  c = Term::ANSIColor.coloring?
  Term::ANSIColor.coloring = options[:color]
  f = Formatter::Pretty.new(nil, io, options)
  f.instance_variable_set('@indent', options[:indent])
  f.visit_multiline_arg(self)
  Term::ANSIColor.coloring = c

  io.rewind
  s = "\n" + io.read + (" " * (options[:indent] - 2))
  s
end

#to_sexpObject

For testing only



125
126
127
# File 'lib/cucumber/ast/table.rb', line 125

def to_sexp #:nodoc:
  [:table, *cells_rows.map{|row| row.to_sexp}]
end

#transposeObject

Returns a new, transposed table. Example:

| a | 7 | 4 | | b | 9 | 2 |

Gets converted into the following:

| a | b | | 7 | 9 | | 4 | 2 |



47
48
49
# File 'lib/cucumber/ast/table.rb', line 47

def transpose
  self.class.new(raw.transpose, @conversion_procs.dup)
end

#verify_column(column_name) ⇒ Object



299
300
301
# File 'lib/cucumber/ast/table.rb', line 299

def verify_column(column_name)
  raise %{The column named "#{column_name}" does not exist} unless raw[0].include?(column_name)
end

#verify_table_width(width) ⇒ Object



303
304
305
# File 'lib/cucumber/ast/table.rb', line 303

def verify_table_width(width)
  raise %{The table must have exactly #{width} columns} unless raw[0].size == width
end