Class: FlatKit::Sort

Inherits:
Object
  • Object
show all
Defined in:
lib/flat_kit/sort.rb

Overview

Internal: Sorts an Input and sends the sorted records to an Output

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input:, output:, compare_fields:, input_fallback: "auto", output_fallback: "auto") ⇒ Sort

Returns a new instance of Sort.



9
10
11
12
13
14
15
# File 'lib/flat_kit/sort.rb', line 9

def initialize(input:, output:, compare_fields:, input_fallback: "auto", output_fallback: "auto")
  @compare_fields = compare_fields
  @reader = ::FlatKit::Reader.create_reader_from_path(path: input, compare_fields: @compare_fields,
                                                      fallback: input_fallback)
  @writer = ::FlatKit::Writer.create_writer_from_path(path: output, fallback: output_fallback,
                                                      reader_format: @reader.format_name)
end

Instance Attribute Details

#compare_fieldsObject (readonly)

Returns the value of attribute compare_fields.



7
8
9
# File 'lib/flat_kit/sort.rb', line 7

def compare_fields
  @compare_fields
end

#readerObject (readonly)

Returns the value of attribute reader.



7
8
9
# File 'lib/flat_kit/sort.rb', line 7

def reader
  @reader
end

#writerObject (readonly)

Returns the value of attribute writer.



7
8
9
# File 'lib/flat_kit/sort.rb', line 7

def writer
  @writer
end

Instance Method Details

#callObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/flat_kit/sort.rb', line 17

def call
  ::FlatKit.logger.info "Sorting #{reader.source} into #{writer.destination} using key #{compare_fields.join(', ')}"
  records = [].tap do |a|
    reader.each do |r|
      a << r
    end
  end
  ::FlatKit.logger.info "Read #{reader.count} records into #{records.size} element array"
  records.sort!
  ::FlatKit.logger.info "Sorted #{records.size} records"
  records.each do |r|
    writer.write(r)
  end
  writer.close
  ::FlatKit.logger.info "Wrote #{writer.count} records to #{writer.destination}"
end