Class: CSVUtils::RowReader

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

Overview

Reads rows from a CSV positioned at its first line, keeping the physical line each row starts on. CSV counts rows, so a quoted value with a line break would make its line numbers fall behind. The byte order mark is stripped from the first row, and rows CSV can't parse raise MalformedRowError.

Examples:

reader = CSVUtils::RowReader.new(csv)
headers = reader.shift
while (row = reader.shift)
  puts "#{reader.lineno}: #{row.inspect}"
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv) ⇒ RowReader

Returns a new instance of RowReader.

Parameters:

  • csv (CSV, CSVWrapper) —

    positioned at the first line



21
22
23
24
25
26
# File 'lib/csv_utils/row_reader.rb', line 21

def initialize(csv)
  @csv = csv
  @last_line = 0
  @row = nil
  @prev_row = nil
end

Instance Attribute Details

#lineno ⇒ Integer? (readonly)

Returns line the last row read starts on, counting the first line as 1.

Returns:

  • (Integer, nil) —

    line the last row read starts on, counting the first line as 1



16
17
18
# File 'lib/csv_utils/row_reader.rb', line 16

def lineno
  @lineno
end

#prev_row ⇒ Array<String>? (readonly)

Returns the row read before the last one.

Returns:

  • (Array<String>, nil) —

    the row read before the last one



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

def prev_row
  @prev_row
end

Instance Method Details

#shift ⇒ Array<String>?

Returns the next row, nil at the end.

Returns:

  • (Array<String>, nil) —

    the next row, nil at the end

Raises:

  • (MalformedRowError) —

    for a row CSV can't parse, with the line it starts on

  • (CSV::InvalidEncodingError) —

    for bytes that don't match the encoding; CSV raises it when it buffers them, ahead of the rows before them, with the right line already



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/csv_utils/row_reader.rb', line 32

def shift
  row = @csv.shift
  @lineno = @last_line + 1
  count_lines(row) if row
  @prev_row = @row
  @row = row
rescue CSV::InvalidEncodingError
  raise
rescue CSV::MalformedCSVError => e
  raise MalformedRowError.new(e.message.delete_suffix(" in line #{e.line_number}."), @last_line + 1, @row)
end