Completed
Push — master ( 78aeb6...ebf929 )
by Marcelo
01:14
created

MappedColumnsParser.parse()   A

Complexity

Conditions 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
1
require "csv"
2
3
module Koine
4
  module Csv
5
    class MappedColumnsParser < CsvParser
6
      attr_reader :column_names
7
8
      def initialize(options = {})
9
        super(options)
10
        @column_names = options.fetch(:column_names)
11
      end
12
13
      def parse(contents, &block)
14
        mapped = []
15
        CSV.parse(contents, parser_options) do |row|
16
          new_row = {}
17
          row.each_with_index do |value, index|
18
            new_row[column_name(index)] = value
19
          end
20
          mapped << new_row
21
        end
22
        block_given? ? mapped.each(&block) : mapped
23
      end
24
25
      private
26
27
      def column_name(index)
28
        column_names.fetch(index)
29
      end
30
    end
31
  end
32
end
33