Class: Sycsvpro::Sorter
Overview
Sorts an input file based on a column sort filter
Instance Attribute Summary collapse
-
#col_type_filter ⇒ Object
readonly
column type filter.
-
#desc ⇒ Object
readonly
sort order descending or ascending.
-
#infile ⇒ Object
readonly
file of the data to sort.
-
#outfile ⇒ Object
readonly
file to write the sorted data to.
-
#row_filter ⇒ Object
readonly
row filter.
-
#sorted_rows ⇒ Object
readonly
sorted rows.
Instance Method Summary collapse
-
#execute ⇒ Object
Sorts the data of the infile.
-
#initialize(options = {}) ⇒ Sorter
constructor
Creates a Sorter and takes as options infile, outfile, rows, cols including types and a date format for the date columns to sort (optional).
Methods included from Dsl
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(={}) @infile = [:infile] @outfile = [:outfile] @desc = [:desc] || false @row_filter = RowFilter.new([:rows]) @col_type_filter = ColumnTypeFilter.new([:cols], df: [:df]) @sorted_rows = [] end |
Instance Attribute Details
#col_type_filter ⇒ Object (readonly)
column type filter
20 21 22 |
# File 'lib/sycsvpro/sorter.rb', line 20 def col_type_filter @col_type_filter end |
#desc ⇒ Object (readonly)
sort order descending or ascending
24 25 26 |
# File 'lib/sycsvpro/sorter.rb', line 24 def desc @desc end |
#infile ⇒ Object (readonly)
file of the data to sort
14 15 16 |
# File 'lib/sycsvpro/sorter.rb', line 14 def infile @infile end |
#outfile ⇒ Object (readonly)
file to write the sorted data to
16 17 18 |
# File 'lib/sycsvpro/sorter.rb', line 16 def outfile @outfile end |
#row_filter ⇒ Object (readonly)
row filter
18 19 20 |
# File 'lib/sycsvpro/sorter.rb', line 18 def row_filter @row_filter end |
#sorted_rows ⇒ Object (readonly)
sorted rows
22 23 24 |
# File 'lib/sycsvpro/sorter.rb', line 22 def sorted_rows @sorted_rows end |
Instance Method Details
#execute ⇒ Object
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 |