MappedColumnsParser.initialize()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 5
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
        @column_names = options.fetch(:column_names)
10
        options.delete(:column_names)
11
        super(options)
12
      end
13
14
      def parse(contents, &block)
15
        mapped = []
16
        CSV.parse(contents, parser_options) do |row|
17
          new_row = {}
18
          row.each_with_index do |value, index|
19
            new_row[column_name(index)] = value
20
          end
21
          mapped << new_row
22
        end
23
        block_given? ? mapped.each(&block) : mapped
24
      end
25
26
      private
27
28
      def column_name(index)
29
        column_names.fetch(index)
30
      end
31
    end
32
  end
33
end
34