Class: CSVUtils::CSVExtender
- Inherits:
-
Object
- Object
- CSVUtils::CSVExtender
- Defined in:
- lib/csv_utils/csv_extender.rb
Overview
Copies a CSV file to a new one with extra columns added to every row.
Instance Method Summary collapse
-
#append(additional_headers) {|row, headers| ... } ⇒ void
Appends columns one row at a time, then closes the files it opened.
-
#append_in_batches(additional_headers, batch_size = 1_000) {|batch, headers| ... } ⇒ void
Appends columns a batch of rows at a time, for lookups that are cheaper in bulk (ex: one database query per batch), then closes the files it opened.
-
#initialize(src_csv, dest_csv, csv_options = {}) ⇒ CSVExtender
constructor
A new instance of CSVExtender.
Constructor Details
#initialize(src_csv, dest_csv, csv_options = {}) ⇒ CSVExtender
Returns a new instance of CSVExtender.
14 15 16 17 |
# File 'lib/csv_utils/csv_extender.rb', line 14 def initialize(src_csv, dest_csv, = {}) @src_csv = CSVUtils::CSVWrapper.new(src_csv, 'rb', EncodingOptions.read()) @dest_csv = CSVUtils::CSVWrapper.new(dest_csv, 'wb', EncodingOptions.write()) end |
Instance Method Details
#append(additional_headers) {|row, headers| ... } ⇒ void
This method returns an undefined value.
Appends columns one row at a time, then closes the files it opened.
25 26 27 28 29 30 31 32 |
# File 'lib/csv_utils/csv_extender.rb', line 25 def append(additional_headers) process(additional_headers) do |current_headers| while (row = @src_csv.shift) additional_columns = yield row, current_headers @dest_csv << (row + additional_columns) end end end |
#append_in_batches(additional_headers, batch_size = 1_000) {|batch, headers| ... } ⇒ void
This method returns an undefined value.
Appends columns a batch of rows at a time, for lookups that are cheaper in bulk (ex: one database query per batch), then closes the files it opened.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/csv_utils/csv_extender.rb', line 42 def append_in_batches(additional_headers, batch_size = 1_000) process(additional_headers) do |current_headers| batch = [] process_batch_proc = proc do additional_rows = yield batch, current_headers batch.each_with_index do |row, idx| @dest_csv << (row + additional_rows[idx]) end batch = [] end while (row = @src_csv.shift) batch << row process_batch_proc.call if batch.size >= batch_size end process_batch_proc.call if batch.size.positive? end end |