Class: CSVUtils::CSVRowMatcher

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

Overview

Matches rows (hashes of header to value) whose values match a regular expression.

Examples:

matcher = CSVUtils::CSVRowMatcher.new(/error/i, ['status', 'message'])
CSVUtils::CSVIterator.new('logs.csv').select(&matcher)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(regex, columns = :all) ⇒ CSVRowMatcher

Returns a new instance of CSVRowMatcher.

Parameters:

  • regex (Regexp)
  • columns (Array<String>, :all) (defaults to: :all) —

    headers to search



17
18
19
20
# File 'lib/csv_utils/csv_row_matcher.rb', line 17

def initialize(regex, columns = :all)
  self.regex = regex
  self.columns = columns
end

Instance Attribute Details

#columns ⇒ Array<String>, :all

Returns headers to search, or :all for every value.

Returns:

  • (Array<String>, :all) —

    headers to search, or :all for every value



13
14
15
# File 'lib/csv_utils/csv_row_matcher.rb', line 13

def columns
  @columns
end

#regex ⇒ Regexp

Returns:

  • (Regexp)


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

def regex
  @regex
end

Instance Method Details

#match?(row) ⇒ Boolean

Whether any searched value matches. Missing and nil values never match.

Parameters:

  • row (Hash{String => String})

Returns:

  • (Boolean)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/csv_utils/csv_row_matcher.rb', line 25

def match?(row)
  if columns == :all
    row.each_value do |value|
      return true if value&.match?(regex)
    end
  else
    columns.each do |column_name|
      value = row[column_name]
      return true if value&.match?(regex)
    end
  end

  false
end

#to_proc ⇒ Proc

Lets the matcher be passed to Enumerable methods as a block, as in rows.select(&matcher).

Returns:

  • (Proc)


42
43
44
45
46
# File 'lib/csv_utils/csv_row_matcher.rb', line 42

def to_proc
  proc do |row|
    match?(row)
  end
end