Class: CSVMagic::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/csv_magic/reader.rb

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Reader

Returns a new instance of Reader.



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/csv_magic/reader.rb', line 4

def initialize(params)
  @file_handler = FileHandler.new
  @file_handler.load_file(params[:filename])

  @file_path = @file_handler.file_path
  @ignore_first_row = params[:ignore_first_row]
  @mapping = {}
  params[:fields].each do |k, v|
    unless v.empty?
      @mapping[v.downcase.to_sym] = k.to_i - 1
    end
  end
end

Instance Method Details

#eachObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/csv_magic/reader.rb', line 18

def each
  row_number = 1
  CSV_HANDLER.foreach(@file_path, CSVMagic.options) do |csv_row|
    unless row_number == 1 && @ignore_first_row
      row = {}
      @mapping.each do |k, v|
        row[k] = csv_row[v]
      end
      row.class.send(:define_method, :number) { row_number }
      yield(row)
    end
    row_number += 1
  end
end

#remove_fileObject



33
34
35
# File 'lib/csv_magic/reader.rb', line 33

def remove_file
  @file_handler.remove_file
end