Class: Cucumber::MultilineArgument::DataTable

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Core::Ast::DescribesItself, Enumerable
Defined in:
lib/cucumber/multiline_argument/data_table.rb

Overview

Step Definitions that match a plain text Step with a multiline argument table will receive it as an instance of Table. A Table object holds the data of a table parsed from a feature file and lets you access and manipulate the data in different ways.

For example:

Given I have:
  | a | b |
  | c | d |

And a matching StepDefinition:

Given /I have:/ do |table|
  data = table.raw
end

This will store [['a', 'b'], ['c', 'd']] in the data variable.

Defined Under Namespace

Classes: Builder, Cell, Cells, Different, SurplusCell

Constant Summary collapse

NULL_CONVERSIONS =
Hash.new({ :strict => false, :proc => lambda{ |cell_value| cell_value } }).freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, conversion_procs = NULL_CONVERSIONS.dup, header_mappings = {}, header_conversion_proc = nil) ⇒ DataTable

Returns a new instance of DataTable.

Parameters:

  • data (Core::Ast::DataTable)

    the data for the table

  • conversion_procs (Hash) (defaults to: NULL_CONVERSIONS.dup)

    see map_columns!

  • header_mappings (Hash) (defaults to: {})

    see map_headers!

  • header_conversion_proc (Proc) (defaults to: nil)

    see map_headers!

Raises:

  • (ArgumentError)


92
93
94
95
96
97
98
99
100
101
102
# File 'lib/cucumber/multiline_argument/data_table.rb', line 92

def initialize(data, conversion_procs = NULL_CONVERSIONS.dup, header_mappings = {}, header_conversion_proc = nil)
  raise ArgumentError, "data must be a Core::Ast::DataTable" unless data.kind_of? Core::Ast::DataTable
  ast_table = data
  # Verify that it's square
  ast_table.transpose
  @cell_matrix = create_cell_matrix(ast_table)
  @conversion_procs = conversion_procs
  @header_mappings = header_mappings
  @header_conversion_proc = header_conversion_proc
  @ast_table = ast_table
end

Instance Attribute Details

#fileObject

Returns the value of attribute file.



55
56
57
# File 'lib/cucumber/multiline_argument/data_table.rb', line 55

def file
  @file
end

Class Method Details

.default_arg_nameObject

:nodoc:



58
59
60
# File 'lib/cucumber/multiline_argument/data_table.rb', line 58

def self.default_arg_name #:nodoc:
  "table"
end

.from(data, location = Core::Ast::Location.of_caller) ⇒ Object



63
64
65
66
67
68
69
70
71
72
# File 'lib/cucumber/multiline_argument/data_table.rb', line 63

def from(data, location = Core::Ast::Location.of_caller)
  case data
  when Array
    from_array(data, location)
  when String
    parse(data, location)
  else
    raise ArgumentError, "expected data to be a String or an Array."
  end
end

Instance Method Details

#append_to(array) ⇒ Object



104
105
106
# File 'lib/cucumber/multiline_argument/data_table.rb', line 104

def append_to(array)
  array << self
end

#cell_matrixObject

:nodoc:



455
456
457
# File 'lib/cucumber/multiline_argument/data_table.rb', line 455

def cell_matrix #:nodoc:
  @cell_matrix
end

#cells_rowsObject

:nodoc:



441
442
443
444
445
# File 'lib/cucumber/multiline_argument/data_table.rb', line 441

def cells_rows #:nodoc:
  @rows ||= cell_matrix.map do |cell_row|
    Cells.new(self, cell_row)
  end
end

#col_width(col) ⇒ Object

:nodoc:



459
460
461
# File 'lib/cucumber/multiline_argument/data_table.rb', line 459

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

#column_namesObject

:nodoc:



204
205
206
# File 'lib/cucumber/multiline_argument/data_table.rb', line 204

def column_names #:nodoc:
  @col_names ||= cell_matrix[0].map { |cell| cell.value }
end

#columnsObject

:nodoc:



485
486
487
488
489
# File 'lib/cucumber/multiline_argument/data_table.rb', line 485

def columns #:nodoc:
  @columns ||= cell_matrix.transpose.map do |cell_row|
    Cells.new(self, cell_row)
  end
end

#description_for_visitorsObject



481
482
483
# File 'lib/cucumber/multiline_argument/data_table.rb', line 481

def description_for_visitors
  :legacy_table
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.

A Different error is raised if there are missing rows or columns, or surplus rows. An error is not raised for surplus columns. An error is not raised for misplaced (out of sequence) columns. Whether to raise or not raise can be changed by setting values in options to true or false:

  • missing_row : Raise on missing rows (defaults to true)

  • surplus_row : Raise on surplus rows (defaults to true)

  • missing_col : Raise on missing columns (defaults to true)

  • surplus_col : Raise on surplus columns (defaults to false)

  • misplaced_col : Raise on misplaced 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.

Raises:



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/cucumber/multiline_argument/data_table.rb', line 338

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

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

  convert_headers!
  convert_columns!

  original_width = cell_matrix[0].length
  @cell_matrix, other_table_cell_matrix = pad_and_match(@cell_matrix, 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
  misplaced_col = cell_matrix[0] != other_table.cell_matrix[0]

  require_diff_lcs
  cell_matrix.extend(Diff::LCS)
  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] ||
    misplaced_col   && options[:misplaced_col]
  raise Different.new(self) if should_raise
end

#dupObject

Creates a copy of this table, inheriting any column and header mappings registered with #map_column! and #map_headers!.



115
116
117
# File 'lib/cucumber/multiline_argument/data_table.rb', line 115

def dup
  self.class.new(Core::Ast::DataTable.new(raw, location), @conversion_procs.dup, @header_mappings.dup, @header_conversion_proc)
end

#each_cells_row(&proc) ⇒ Object

:nodoc:



214
215
216
# File 'lib/cucumber/multiline_argument/data_table.rb', line 214

def each_cells_row(&proc) #:nodoc:
  cells_rows.each(&proc)
end

#has_text?(text) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


437
438
439
# File 'lib/cucumber/multiline_argument/data_table.rb', line 437

def has_text?(text) #:nodoc:
  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.



148
149
150
# File 'lib/cucumber/multiline_argument/data_table.rb', line 148

def hashes
  @hashes ||= build_hashes
end

#header_cell(col) ⇒ Object

:nodoc:



451
452
453
# File 'lib/cucumber/multiline_argument/data_table.rb', line 451

def header_cell(col) #:nodoc:
  cells_rows[0][col]
end

#headersObject

:nodoc:



447
448
449
# File 'lib/cucumber/multiline_argument/data_table.rb', line 447

def headers #:nodoc:
  raw.first
end

#index(cells) ⇒ Object

:nodoc:



425
426
427
# File 'lib/cucumber/multiline_argument/data_table.rb', line 425

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

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

Returns a new Table with an additional column mapping. See #map_column!



296
297
298
299
300
# File 'lib/cucumber/multiline_argument/data_table.rb', line 296

def map_column(column_name, strict=true, &conversion_proc)
  conversion_procs = @conversion_procs.dup
  conversion_procs[column_name.to_s] = { :strict => strict, :proc => conversion_proc }
  self.class.new(Core::Ast::DataTable.new(raw, location), conversion_procs, @header_mappings.dup, @header_conversion_proc)
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


289
290
291
292
293
# File 'lib/cucumber/multiline_argument/data_table.rb', line 289

def map_column!(column_name, strict=true, &conversion_proc)
  # TODO: Remove this method for 2.0
  @conversion_procs[column_name.to_s] = { :strict => strict, :proc => conversion_proc }
  self
end

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

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



273
274
275
# File 'lib/cucumber/multiline_argument/data_table.rb', line 273

def map_headers(mappings={}, &block)
  self.class.new(Core::Ast::DataTable.new(raw, location), @conversion_procs.dup, mappings, block)
end

#map_headers!(mappings = {}, &block) ⇒ 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'}]

You may also pass in a block if you wish to convert all of the headers:

table.map_headers! { |header| header.downcase }
table.hashes.keys
# => ['phone number', 'address']

When a block is passed in along with a hash then the mappings in the hash take precendence:

table.map_headers!('Address' => 'ADDRESS') { |header| header.downcase }
table.hashes.keys
# => ['phone number', 'ADDRESS']


265
266
267
268
269
270
# File 'lib/cucumber/multiline_argument/data_table.rb', line 265

def map_headers!(mappings={}, &block)
  # TODO: Remove this method for 2.0
  clear_cache!
  @header_mappings = mappings
  @header_conversion_proc = block
end

#match(pattern) ⇒ Object

Matches pattern against the header row of the table. This is used especially for argument transforms.

Example:

| column_1_name | column_2_name |
| x             | y             |

table.match(/table:column_1_name,column_2_name/) #=> non-nil

Note: must use ‘table:’ prefix on match



228
229
230
231
# File 'lib/cucumber/multiline_argument/data_table.rb', line 228

def match(pattern)
  header_to_match = "table:#{headers.join(',')}"
  pattern.match(header_to_match)
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']]


196
197
198
199
200
201
202
# File 'lib/cucumber/multiline_argument/data_table.rb', line 196

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

#rowsObject



208
209
210
211
212
# File 'lib/cucumber/multiline_argument/data_table.rb', line 208

def rows
  hashes.map do |hash|
    hash.values_at *headers
  end
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



180
181
182
183
184
# File 'lib/cucumber/multiline_argument/data_table.rb', line 180

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

#symbolic_hashesObject

Converts this table into an Array of Hashes where the keys are symbols. For example, a Table built from the following plain text:

| foo | Bar | Foo Bar |
| 2   | 3   | 5       |
| 7   | 9   | 16      |

Gets converted into the following:

[{:foo => '2', :bar => '3', :foo_bar => '5'}, {:foo => '7', :bar => '9', :foo_bar => '16'}]


163
164
165
166
# File 'lib/cucumber/multiline_argument/data_table.rb', line 163

def symbolic_hashes
  @header_conversion_proc = lambda { |h| symbolize_key(h) }
  @symbolic_hashes ||= build_hashes
end

#to_hash(cells) ⇒ Object

:nodoc:



415
416
417
418
419
420
421
422
423
# File 'lib/cucumber/multiline_argument/data_table.rb', line 415

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

#to_json(*args) ⇒ Object



491
492
493
# File 'lib/cucumber/multiline_argument/data_table.rb', line 491

def to_json(*args)
  raw.to_json(*args)
end

#to_s(options = {}) ⇒ Object

:nodoc:



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/cucumber/multiline_argument/data_table.rb', line 463

def to_s(options = {}) #:nodoc:
  # TODO: factor out this code so we don't depend on such a big lump of old cruft
  require 'cucumber/formatter/pretty'
  require 'cucumber/formatter/legacy_api/adapter'
  options = {:color => true, :indent => 2, :prefixes => TO_S_PREFIXES}.merge(options)
  io = StringIO.new

  c = Cucumber::Term::ANSIColor.coloring?
  Cucumber::Term::ANSIColor.coloring = options[:color]
  formatter = Formatter::Pretty.new(nil, io, options)
  formatter.instance_variable_set('@indent', options[:indent])
  Formatter::LegacyApi::Ast::MultilineArg.for(self).accept(Formatter::Fanout.new([formatter]))
  Cucumber::Term::ANSIColor.coloring = c
  io.rewind
  s = "\n" + io.read + (" " * (options[:indent] - 2))
  s
end

#to_step_definition_argObject



108
109
110
# File 'lib/cucumber/multiline_argument/data_table.rb', line 108

def to_step_definition_arg
  dup
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 |


130
131
132
# File 'lib/cucumber/multiline_argument/data_table.rb', line 130

def transpose
  self.class.new(Core::Ast::DataTable.new(raw.transpose, location), @conversion_procs.dup, @header_mappings.dup, @header_conversion_proc)
end

#verify_column(column_name) ⇒ Object

:nodoc:



429
430
431
# File 'lib/cucumber/multiline_argument/data_table.rb', line 429

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

#verify_table_width(width) ⇒ Object

:nodoc:



433
434
435
# File 'lib/cucumber/multiline_argument/data_table.rb', line 433

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