Class: FlatKit::Xsv::Reader

Inherits:
Reader
  • Object
show all
Defined in:
lib/flat_kit/xsv/reader.rb

Overview

Internal: Reader class that parses and yields records from xsv files

Instance Attribute Summary collapse

Attributes inherited from Reader

#compare_fields, #source

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Reader

create_reader_from_path, create_readers_from_paths, #format_name

Constructor Details

#initialize(source:, compare_fields: :none, **csv_options) ⇒ Reader

Returns a new instance of Reader.



24
25
26
27
28
29
30
31
# File 'lib/flat_kit/xsv/reader.rb', line 24

def initialize(source:, compare_fields: :none, **csv_options)
  super(source: source, compare_fields: compare_fields)
  @input = ::FlatKit::Input.from(source)
  @count = 0
  @csv_options = Reader.default_csv_options.merge(csv_options)
  @fields = nil
  @csv = CSV.new(input.io, **@csv_options)
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



10
11
12
# File 'lib/flat_kit/xsv/reader.rb', line 10

def count
  @count
end

#fieldsObject (readonly)

Returns the value of attribute fields.



10
11
12
# File 'lib/flat_kit/xsv/reader.rb', line 10

def fields
  @fields
end

#inputObject (readonly)

Returns the value of attribute input.



10
11
12
# File 'lib/flat_kit/xsv/reader.rb', line 10

def input
  @input
end

Class Method Details

.default_csv_optionsObject



16
17
18
19
20
21
22
# File 'lib/flat_kit/xsv/reader.rb', line 16

def self.default_csv_options
  {
    headers: :first_row,
    converters: :numeric,
    return_headers: false,
  }
end

.format_nameObject



12
13
14
# File 'lib/flat_kit/xsv/reader.rb', line 12

def self.format_name
  ::FlatKit::Xsv::Format.format_name
end

Instance Method Details

#eachObject



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/flat_kit/xsv/reader.rb', line 33

def each
  @csv.each do |row|
    @fields = row.headers if @fields.nil?
    record = ::FlatKit::Xsv::Record.new(data: row, compare_fields: compare_fields)
    @count += 1
    yield record
  end
  input.close
rescue StandardError => e
  ::FlatKit.logger.error "Error reading xsv records from #{input.name}: #{e}"
  raise ::FlatKit::Error, e
end