Class: Sycsvpro::Mapper

Inherits:
Object
  • Object
show all
Defined in:
lib/sycsvpro/mapper.rb

Overview

Map values to new values described in a mapping file

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Mapper

Creates new mapper



19
20
21
22
23
24
25
26
# File 'lib/sycsvpro/mapper.rb', line 19

def initialize(options={})
  @infile = options[:infile]
  @outfile = options[:outfile]
  @row_filter = RowFilter.new(options[:row_filter])
  @col_filter = ColumnFilter.new(options[:col_filter])
  @mapper = {}
  init_mapper(options[:mapping])
end

Instance Attribute Details

#col_filterObject (readonly)

filter that is used for columns



16
17
18
# File 'lib/sycsvpro/mapper.rb', line 16

def col_filter
  @col_filter
end

#infileObject (readonly)

infile contains the data that is operated on



8
9
10
# File 'lib/sycsvpro/mapper.rb', line 8

def infile
  @infile
end

#mapperObject (readonly)

file that contains the mappings from existing column values to new values



12
13
14
# File 'lib/sycsvpro/mapper.rb', line 12

def mapper
  @mapper
end

#outfileObject (readonly)

outfile is the file where the result is written to



10
11
12
# File 'lib/sycsvpro/mapper.rb', line 10

def outfile
  @outfile
end

#row_filterObject (readonly)

filter that is used for rows



14
15
16
# File 'lib/sycsvpro/mapper.rb', line 14

def row_filter
  @row_filter
end

Instance Method Details

#executeObject

Executes the mapper



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/sycsvpro/mapper.rb', line 29

def execute
  File.open(outfile, 'w') do |out|
    File.new(infile, 'r').each_with_index do |line, index|
      result = col_filter.process(row_filter.process(line, row: index))
      next if result.chomp.empty? or result.nil?
      mapper.each do |from, to|
        result = result.chomp.gsub(/(?<=^|;)#{from}(?=;|$)/, to)
      end
      out.puts result
    end
  end
end