Class: Loady::CsvLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/loady/csv_loader.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCsvLoader



8
9
10
11
12
# File 'lib/loady/csv_loader.rb', line 8

def initialize
  @success = 0
  @warning = 0
  @line_number = 0
end

Class Method Details

.readObject



33
34
35
# File 'lib/loady/csv_loader.rb', line 33

def read(*, **, &)
  new.read(*, **, &)
end

Instance Method Details

#read(filename, options = {}, &block) ⇒ Object

valid options:

skip_first_row: true                       -- default = false
logger: Logger.new('/somewhere/file.log')  -- default = Logger.new(STDOUT)
plus any valid options you can pass to CSV.new:
  see https://ruby.github.io/csv/CSV.html#class-CSV-label-Options


19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/loady/csv_loader.rb', line 19

def read(filename, options = {}, &block)
  @logger = options.delete(:logger) || default_logger
  options[:headers] ||= options.delete(:skip_first_row)

  CSV.foreach(filename, **options) do |line|
    readline line, &block
  end
  @logger.info "Finished. Loaded #{@success} rows. #{@warning} skipped rows."
rescue CSV::MalformedCSVError => e
  @logger.error e.message
  @logger.error "Stopped Loading after #{@success} rows. #{@warning} skipped rows."
end