Class: Sycsvpro::Sorter

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

Overview

Sorts an input file based on a column sort filter

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Dsl

#rows, #unstring, #write_to

Constructor Details

#initialize(options = {}) ⇒ Sorter

Creates a Sorter and takes as options infile, outfile, rows, cols including types and a date format for the date columns to sort (optional)



28
29
30
31
32
33
34
35
# File 'lib/sycsvpro/sorter.rb', line 28

def initialize(options={})
  @infile          = options[:infile]
  @outfile         = options[:outfile]
  @desc            = options[:desc] || false
  @row_filter      = RowFilter.new(options[:rows])
  @col_type_filter = ColumnTypeFilter.new(options[:cols], df: options[:df])
  @sorted_rows     = []
end

Instance Attribute Details

#col_type_filterObject (readonly)

column type filter



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

def col_type_filter
  @col_type_filter
end

#descObject (readonly)

sort order descending or ascending



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

def desc
  @desc
end

#infileObject (readonly)

file of the data to sort



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

def infile
  @infile
end

#outfileObject (readonly)

file to write the sorted data to



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

def outfile
  @outfile
end

#row_filterObject (readonly)

row filter



18
19
20
# File 'lib/sycsvpro/sorter.rb', line 18

def row_filter
  @row_filter
end

#sorted_rowsObject (readonly)

sorted rows



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

def sorted_rows
  @sorted_rows
end

Instance Method Details

#executeObject

Sorts the data of the infile



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/sycsvpro/sorter.rb', line 38

def execute
  rows = File.readlines(infile)

  rows.each_with_index do |line, index|
    filtered = col_type_filter.process(row_filter.process(line, row: index))
    next if filtered.nil?
    sorted_rows << (filtered << index)
  end

  File.open(outfile, 'w') do |out|
    if desc
      sorted_rows.compact.sort.reverse.each do |row|
        out.puts unstring(rows[row.last])
      end
    else
      sorted_rows.compact.sort.each do |row|
        out.puts unstring(rows[row.last])
      end
    end
  end
end