Class: CSVUtils::CSVIterator::RowWrapper

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

Overview

A row as a hash of header to value that knows its line number in the file.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#lineno ⇒ Integer

Returns line the row starts on in the file, counting the header row as line 1. A quoted value with a line break spans several lines, so this can differ from the row's position in the file.

Returns:

  • (Integer) —

    line the row starts on in the file, counting the header row as line 1. A quoted value with a line break spans several lines, so this can differ from the row's position in the file.



20
21
22
# File 'lib/csv_utils/csv_iterator.rb', line 20

def lineno
  @lineno
end

Class Method Details

.create(headers, row, lineno) ⇒ RowWrapper

Parameters:

  • headers (Array<String>)
  • row (Array<String>)
  • lineno (Integer)

Returns:



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

def self.create(headers, row, lineno)
  row_wrapper = new
  row_wrapper.lineno = lineno
  # an index loop instead of headers.zip(row), which allocates an array per column for every row
  idx = 0
  size = headers.size
  while idx < size
    row_wrapper[headers[idx]] = row[idx]
    idx += 1
  end
  row_wrapper
end

Instance Method Details

#to_pretty_s ⇒ String

Numbered "header: value" lines for the non-blank values, as csv-grep prints them.

Returns:

  • (String)


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

def to_pretty_s
  reject { |_, v| v.nil? || v.strip.empty? }
    .each_with_index
    .map { |(k, v), idx| format('  %-3d %s: %s', idx + 1, k, v) }
    .join("\n") + "\n"
end