Class: Cucumber::Ast::Table
- Includes:
- Enumerable
- Defined in:
- lib/cucumber/ast/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.
Direct Known Subclasses
Defined Under Namespace
Classes: Cell, Cells, Different, SurplusCell
Constant Summary collapse
- NULL_CONVERSIONS =
Hash.new(lambda{ |cell_value| cell_value }).freeze
Instance Attribute Summary collapse
-
#file ⇒ Object
Returns the value of attribute file.
Class Method Summary collapse
-
.default_arg_name ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#accept(visitor) ⇒ Object
:nodoc:.
-
#arguments_replaced(arguments) ⇒ Object
:nodoc:.
-
#cell_matrix ⇒ Object
:nodoc:.
-
#cells_rows ⇒ Object
:nodoc:.
-
#col_width(col) ⇒ Object
:nodoc:.
-
#diff!(other_table, options = {}) ⇒ Object
Compares
other_table
to self. -
#dup ⇒ Object
Creates a copy of this table, inheriting any column mappings.
-
#each_cells_row(&proc) ⇒ Object
:nodoc:.
-
#has_text?(text) ⇒ Boolean
:nodoc:.
-
#hashes ⇒ Object
Converts this table into an Array of Hash where the keys of each Hash are the headers in the table.
-
#header_cell(col) ⇒ Object
:nodoc:.
-
#headers ⇒ Object
:nodoc:.
-
#index(cells) ⇒ Object
:nodoc:.
-
#initialize(raw, conversion_procs = NULL_CONVERSIONS.dup) ⇒ Table
constructor
Creates a new instance.
-
#map_column!(column_name, strict = true, &conversion_proc) ⇒ Object
Change how #hashes converts column values.
-
#map_headers(mappings = {}) ⇒ Object
Returns a new Table where the headers are redefined.
-
#map_headers!(mappings = {}, &block) ⇒ Object
Redefines the table headers.
-
#match(pattern) ⇒ Object
Matches
pattern
against the header row of the table. -
#raw ⇒ Object
Gets the raw data of this table.
-
#rows ⇒ Object
Same as #raw, but skips the first (header) row.
-
#rows_hash ⇒ Object
Converts this table into a Hash where the first column is used as keys and the second column is used as values.
-
#to_hash(cells) ⇒ Object
:nodoc:.
-
#to_s(options = {}) ⇒ Object
:nodoc:.
-
#to_sexp ⇒ Object
For testing only.
-
#transpose ⇒ Object
Returns a new, transposed table.
-
#verify_column(column_name) ⇒ Object
:nodoc:.
-
#verify_table_width(width) ⇒ Object
:nodoc:.
Constructor Details
#initialize(raw, conversion_procs = NULL_CONVERSIONS.dup) ⇒ Table
Creates a new instance. raw
should be an Array of Array of String or an Array of Hash (similar to what #hashes returns). You don’t typically create your own Table objects - Cucumber will do it internally and pass them to your Step Definitions.
47 48 49 50 51 52 53 54 55 56 |
# File 'lib/cucumber/ast/table.rb', line 47 def initialize(raw, conversion_procs = NULL_CONVERSIONS.dup) @cells_class = Cells @cell_class = Cell raw = ensure_array_of_array(raw) # Verify that it's square transposed = raw.transpose create_cell_matrix(raw) @conversion_procs = conversion_procs end |
Instance Attribute Details
#file ⇒ Object
Returns the value of attribute file.
36 37 38 |
# File 'lib/cucumber/ast/table.rb', line 36 def file @file end |
Class Method Details
.default_arg_name ⇒ Object
:nodoc:
38 39 40 |
# File 'lib/cucumber/ast/table.rb', line 38 def self.default_arg_name #:nodoc: "table" end |
Instance Method Details
#accept(visitor) ⇒ Object
:nodoc:
145 146 147 148 149 150 151 |
# File 'lib/cucumber/ast/table.rb', line 145 def accept(visitor) #:nodoc: return if Cucumber.wants_to_quit cells_rows.each do |row| visitor.visit_table_row(row) end nil end |
#arguments_replaced(arguments) ⇒ Object
:nodoc:
371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
# File 'lib/cucumber/ast/table.rb', line 371 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_matrix ⇒ Object
:nodoc:
404 405 406 |
# File 'lib/cucumber/ast/table.rb', line 404 def cell_matrix #:nodoc: @cell_matrix end |
#cells_rows ⇒ Object
:nodoc:
390 391 392 393 394 |
# File 'lib/cucumber/ast/table.rb', line 390 def cells_rows #:nodoc: @rows ||= cell_matrix.map do |cell_row| @cells_class.new(self, cell_row) end end |
#col_width(col) ⇒ Object
:nodoc:
408 409 410 |
# File 'lib/cucumber/ast/table.rb', line 408 def col_width(col) #:nodoc: 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.
A Different error 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:
-
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)
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.
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/cucumber/ast/table.rb', line 282 def diff!(other_table, ={}) = {:missing_row => true, :surplus_row => true, :missing_col => true, :surplus_col => false}.merge() 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 && [:missing_row] || insert_row_pos && [:surplus_row] || missing_col && [:missing_col] || surplus_col && [:surplus_col] raise Different.new(self) if should_raise end |
#dup ⇒ Object
Creates a copy of this table, inheriting any column mappings. registered with #map_headers!
61 62 63 |
# File 'lib/cucumber/ast/table.rb', line 61 def dup self.class.new(raw.dup, @conversion_procs.dup) end |
#each_cells_row(&proc) ⇒ Object
:nodoc:
141 142 143 |
# File 'lib/cucumber/ast/table.rb', line 141 def each_cells_row(&proc) #:nodoc: cells_rows.each(&proc) end |
#has_text?(text) ⇒ Boolean
:nodoc:
386 387 388 |
# File 'lib/cucumber/ast/table.rb', line 386 def has_text?(text) #:nodoc: raw.flatten.compact.detect{|cell_value| cell_value.index(text)} end |
#hashes ⇒ Object
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.
94 95 96 97 98 |
# File 'lib/cucumber/ast/table.rb', line 94 def hashes @hashes ||= cells_rows[1..-1].map do |row| row.to_hash end end |
#header_cell(col) ⇒ Object
:nodoc:
400 401 402 |
# File 'lib/cucumber/ast/table.rb', line 400 def header_cell(col) #:nodoc: cells_rows[0][col] end |
#headers ⇒ Object
:nodoc:
396 397 398 |
# File 'lib/cucumber/ast/table.rb', line 396 def headers #:nodoc: raw.first end |
#index(cells) ⇒ Object
:nodoc:
359 360 361 |
# File 'lib/cucumber/ast/table.rb', line 359 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
243 244 245 246 |
# File 'lib/cucumber/ast/table.rb', line 243 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!
225 226 227 228 229 |
# File 'lib/cucumber/ast/table.rb', line 225 def map_headers(mappings={}) table = self.dup table.map_headers!(mappings) table 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']
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# File 'lib/cucumber/ast/table.rb', line 205 def map_headers!(mappings={}, &block) header_cells = cell_matrix[0] if block_given? header_values = header_cells.map { |cell| cell.value } - mappings.keys mappings = mappings.merge(Hash[*header_values.zip(header_values.map(&block)).flatten]) end mappings.each_pair do |pre, post| mapped_cells = header_cells.select{|cell| pre === cell.value} raise "No headers matched #{pre.inspect}" if mapped_cells.empty? raise "#{mapped_cells.length} headers matched #{pre.inspect}: #{mapped_cells.map{|c| c.value}.inspect}" if mapped_cells.length > 1 mapped_cells[0].value = post if @conversion_procs.has_key?(pre) @conversion_procs[post] = @conversion_procs.delete(pre) end end 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
163 164 165 166 |
# File 'lib/cucumber/ast/table.rb', line 163 def match(pattern) header_to_match = "table:#{headers.join(',')}" pattern.match(header_to_match) end |
#raw ⇒ Object
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']]
128 129 130 131 132 133 134 |
# File 'lib/cucumber/ast/table.rb', line 128 def raw cell_matrix.map do |row| row.map do |cell| cell.value end end end |
#rows ⇒ Object
Same as #raw, but skips the first (header) row
137 138 139 |
# File 'lib/cucumber/ast/table.rb', line 137 def rows raw[1..-1] end |
#rows_hash ⇒ Object
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
112 113 114 115 116 |
# File 'lib/cucumber/ast/table.rb', line 112 def rows_hash return @rows_hash if @rows_hash verify_table_width(2) @rows_hash = self.transpose.hashes[0] end |
#to_hash(cells) ⇒ Object
:nodoc:
348 349 350 351 352 353 354 355 356 357 |
# File 'lib/cucumber/ast/table.rb', line 348 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
:nodoc:
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 |
# File 'lib/cucumber/ast/table.rb', line 412 def to_s( = {}) #:nodoc: require 'cucumber/formatter/pretty' = {:color => true, :indent => 2, :prefixes => TO_S_PREFIXES}.merge() io = StringIO.new c = Term::ANSIColor.coloring? Term::ANSIColor.coloring = [:color] formatter = Formatter::Pretty.new(nil, io, ) formatter.instance_variable_set('@indent', [:indent]) TreeWalker.new(nil, [formatter]).visit_multiline_arg(self) Term::ANSIColor.coloring = c io.rewind s = "\n" + io.read + (" " * ([:indent] - 2)) s end |
#to_sexp ⇒ Object
For testing only
169 170 171 |
# File 'lib/cucumber/ast/table.rb', line 169 def to_sexp #:nodoc: [:table, *cells_rows.map{|row| row.to_sexp}] end |
#transpose ⇒ Object
Returns a new, transposed table. Example:
| a | 7 | 4 |
| b | 9 | 2 |
Gets converted into the following:
| a | b |
| 7 | 9 |
| 4 | 2 |
76 77 78 |
# File 'lib/cucumber/ast/table.rb', line 76 def transpose self.class.new(raw.transpose, @conversion_procs.dup) end |
#verify_column(column_name) ⇒ Object
:nodoc:
363 364 365 |
# File 'lib/cucumber/ast/table.rb', line 363 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:
367 368 369 |
# File 'lib/cucumber/ast/table.rb', line 367 def verify_table_width(width) #:nodoc: raise %{The table must have exactly #{width} columns} unless raw[0].size == width end |