module CSVDecision::Header

Parse the CSV file's header row. These methods are only required at table load time. @api private

Constants

COLUMN_NAME

Regular expression string for a column name. More lenient than a Ruby method name - note any spaces will have been replaced with underscores.

COLUMN_NAME_RE

Regular expression for matching a column name.

COLUMN_TYPE

Column types recognised in the header row.

Public Class Methods

column_name?(column_name) click to toggle source

Return true if column name is valid.

@param column_name [String] @return [Boolean]

# File lib/csv_decision/header.rb, line 30
def self.column_name?(column_name)
  COLUMN_NAME_RE.match?(column_name)
end
parse(table:, matchers:) click to toggle source

Parse the header row, and the defaults row if present. @param table [CSVDecision::Table] Decision table being parsed. @param matchers [Array<Matchers::Matcher>] Array of special cell matchers. @return [CSVDecision::Columns] Table columns object.

# File lib/csv_decision/header.rb, line 59
def self.parse(table:, matchers:)
  # Parse the header row
  table.columns = CSVDecision::Columns.new(table)

  # Parse the defaults row if present
  return table.columns if table.columns.defaults.blank?

  table.columns.defaults =
    Defaults.parse(columns: table.columns, matchers: matchers.outs, row: table.rows.shift)

  table.columns
end
row?(row) click to toggle source

Check if the given row contains a recognisable header cell.

@param row [Array<String>] Header row. @return [Boolean] Return true if the row looks like a header.

# File lib/csv_decision/header.rb, line 38
def self.row?(row)
  row.any? { |cell| COLUMN_TYPE.match?(cell) }
end
strip_empty_columns(rows:) click to toggle source

Strip empty columns from all data rows.

@param rows [Array<Array<String>>] Data rows. @return [Array<Array<String>>] Data array after removing any empty columns

and the header row.
# File lib/csv_decision/header.rb, line 47
def self.strip_empty_columns(rows:)
  empty_cols = empty_columns?(row: rows.first)
  Data.strip_columns(data: rows, empty_columns: empty_cols) if empty_cols

  # Remove header row from the data array.
  rows.shift
end

Private Class Methods

empty_columns?(row:) click to toggle source

Build an array of all empty column indices. @param row [Array] @return [false, Array<Integer>]

# File lib/csv_decision/header.rb, line 75
def self.empty_columns?(row:)
  result = []
  row&.each_with_index { |cell, index| result << index if cell == '' }

  result.empty? ? false : result
end