Class: Zizia::CsvParser

Inherits:
Parser
  • Object
show all
Defined in:
lib/zizia/parsers/csv_parser.rb

Overview

A parser for CSV files. A single ‘InputRecord` is returned for each row parsed from the input.

Validates the format of the CSV, generating a single error the file is malformed. This error gives the line number and a message for the first badly formatted row.

See Also:

Constant Summary collapse

DEFAULT_VALIDATORS =
[CsvFormatValidator.new].freeze
EXTENSION =
'.csv'

Instance Attribute Summary

Attributes inherited from Parser

#errors, #file, #validators

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Parser

for, #initialize, #valid?, #validate, #validate!

Constructor Details

This class inherits a constructor from Zizia::Parser

Class Method Details

.match?(file:, **_opts) ⇒ Boolean

Matches all ‘.csv’ filenames.

Returns:

  • (Boolean)


22
23
24
25
26
# File 'lib/zizia/parsers/csv_parser.rb', line 22

def match?(file:, **_opts)
  File.extname(file) == EXTENSION
rescue TypeError
  false
end

Instance Method Details

#recordsObject

Gives a record for each line in the .csv

See Also:



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/zizia/parsers/csv_parser.rb', line 33

def records
  return enum_for(:records) unless block_given?

  file.rewind

  CSV.parse(file.read, headers: true).each do |row|
    yield InputRecord.from(metadata: row)
  end
rescue CSV::MalformedCSVError => e
  Rails.logger.error "[zizia] The file #{file} could not be parsed as CSV: #{e}"
end