Class: CsvMapper::Reader

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

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Reader

Returns a new instance of Reader.



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

def initialize(params)
  @file_handler = CsvMapper::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



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

def each
  row_number = 1
  FasterCSV.foreach(@file_path, CsvMapper.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



34
35
36
# File 'lib/csv_mapper/reader.rb', line 34

def remove_file
  @file_handler.remove_file
end