Class: Sycsvpro::Allocator

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

Overview

Allocates columns to a key column

infile.csv

| Name | Product | | A | X1 | | B | Y2 | | A | W10 |

outfile.csv

| A | X1 | W10 | | B | Y2 | |

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Allocator

Creates a new allocator. Options are infile, outfile, key, rows and columns to allocate to key



31
32
33
34
35
36
37
# File 'lib/sycsvpro/allocator.rb', line 31

def initialize(options={})
  @infile     = options[:infile]
  @outfile    = options[:outfile]
  @key_filter = ColumnFilter.new(options[:key], df: options[:df])
  @row_filter = RowFilter.new(options[:rows], df: options[:df])
  @col_filter = ColumnFilter.new(options[:cols])
end

Instance Attribute Details

#col_filterObject (readonly)

Filter for columns to allocate



26
27
28
# File 'lib/sycsvpro/allocator.rb', line 26

def col_filter
  @col_filter
end

#infileObject (readonly)

File from that values are read



20
21
22
# File 'lib/sycsvpro/allocator.rb', line 20

def infile
  @infile
end

#key_filterObject (readonly)

Filter for the key column that the values are allocated at



28
29
30
# File 'lib/sycsvpro/allocator.rb', line 28

def key_filter
  @key_filter
end

#outfileObject (readonly)

File to that result of allocation is written



22
23
24
# File 'lib/sycsvpro/allocator.rb', line 22

def outfile
  @outfile
end

#row_filterObject (readonly)

Filter for rows to consider



24
25
26
# File 'lib/sycsvpro/allocator.rb', line 24

def row_filter
  @row_filter
end

Instance Method Details

#executeObject

Executes the allocator and assigns column values to the key



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/sycsvpro/allocator.rb', line 40

def execute
  allocation = {}
  File.open(infile).each_with_index do |line, index|
    row = row_filter.process(line, row: index)
    next if row.nil? or row.empty?
    key = key_filter.process(row)
    allocation[key] = [] if allocation[key].nil?
    allocation[key] << col_filter.process(row).split(';') 
  end

  File.open(outfile, 'w') do |out|
    allocation.each do |key, values|
      out.puts "#{key};#{values.flatten.uniq.sort.join(';')}"
    end
  end
end