Class: Sycsvpro::Transposer

Inherits:
Object
  • Object
show all
Includes:
Dsl
Defined in:
lib/sycsvpro/transposer.rb

Overview

Tranposes rows to columns and vice versa

Example

infile.csv | Year | SP | RP | Total | SP-O | RP-O | O | | —- | – | – | —– | —- | —- | — | | | 10 | 20 | 30 | 100 | 40 | 140 | | 2008 | 5 | 10 | 15 | 10 | 20 | 10 | | 2009 | 2 | 5 | 5 | 20 | 10 | 30 | | 2010 | 3 | 5 | 10 | 70 | 10 | 100 |

outfile.csv | Year | | 2008 | 2009 | 2010 | | —– | — | —- | —- | —- | | SP | 10 | 5 | 5 | 3 | | RP | 20 | 10 | 10 | 5 | | Total | 30 | 15 | 15 | 10 | | SP-O | 100 | 10 | 10 | 70 | | RP-O | 40 | 20 | 20 | 10 | | O | 140 | 10 | 30 | 100 |

Constant Summary

Constants included from Dsl

Dsl::COMMA_SPLITTER_REGEX

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Dsl

#clean_up, #params, #rows, #split_by_comma_regex, #str2utf8, #unstring, #write_to

Constructor Details

#initialize(options = {}) ⇒ Transposer

Create a new Transpose :call-seq:

Sycsvpro::Transpose(infile:  "infile.csv",
                    outfile: "outfile.csv",
                    rows:    "0,3-5",
                    cols:    "1,3").execute


45
46
47
48
49
50
# File 'lib/sycsvpro/transposer.rb', line 45

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

Instance Attribute Details

#col_filterObject (readonly)

filter that is used for columns



37
38
39
# File 'lib/sycsvpro/transposer.rb', line 37

def col_filter
  @col_filter
end

#infileObject (readonly)

infile contains the data that is operated on



31
32
33
# File 'lib/sycsvpro/transposer.rb', line 31

def infile
  @infile
end

#outfileObject (readonly)

outfile is the file where the result is written to



33
34
35
# File 'lib/sycsvpro/transposer.rb', line 33

def outfile
  @outfile
end

#row_filterObject (readonly)

filter that is used for rows



35
36
37
# File 'lib/sycsvpro/transposer.rb', line 35

def row_filter
  @row_filter
end

Instance Method Details

#executeObject

Executes the transpose by reading the infile and writing the result to the outfile



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/sycsvpro/transposer.rb', line 54

def execute
  transpose = {}

  File.open(@infile).each_with_index do |line, index|
    line = unstring(line)
    next if line.empty?

    result = @col_filter.process(@row_filter.process(line, row: index))
    next if result.nil?

    result.split(';').each_with_index do |col, index|
      transpose[index] ||= []
      transpose[index] << col
    end
  end

  File.open(@outfile, 'w') do |out|
    transpose.values.each { |value| out.puts value.join(';') }
  end
end