Class: Eco::CSV::Stream

Inherits:
Object show all
Includes:
Language::AuxiliarLogger
Defined in:
lib/eco/csv/stream.rb

Instance Attribute Summary collapse

Attributes included from Language::AuxiliarLogger

#logger

Instance Method Summary collapse

Methods included from Language::AuxiliarLogger

#log

Constructor Details

#initialize(filename, **kargs) ⇒ Stream

Returns a new instance of Stream.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
# File 'lib/eco/csv/stream.rb', line 8

def initialize(filename, **kargs)
  raise ArgumentError, "File '#{filename}' does not exist" unless ::File.exist?(filename)

  @filename = filename
  @params   = {
    headers:     true,
    skip_blanks: true
  }.merge(kargs)
  init
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



6
7
8
# File 'lib/eco/csv/stream.rb', line 6

def filename
  @filename
end

Instance Method Details

#for_each(start_at_idx: 0) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/eco/csv/stream.rb', line 19

def for_each(start_at_idx: 0)
  raise ArgumentError, 'Expecting block, but not given.' unless block_given?

  move_to_idx(start_at_idx)

  yield(row, next_idx) while (self.row = csv.shift)
rescue StandardError => err
  self.exception = err
  raise
ensure
  (fd.close; @fd = nil) if fd.is_a?(::File) # rubocop:disable Style/Semicolon
  if exception
    # Give some feedback if it crashes
    msg  = []
    msg << "Last row IDX: #{idx}"
    msg << "Last row content: #{row.to_h.pretty_inspect}"
    puts msg
    log(:debug) { msg.join("\n") }
  end
end

#move_to_idx(start_at_idx) ⇒ Object



40
41
42
43
# File 'lib/eco/csv/stream.rb', line 40

def move_to_idx(start_at_idx)
  start_at_idx ||= 0
  next_idx while (idx < start_at_idx) && (self.row = csv.shift)
end