Class: CSVUtils::CSVTransformer

Inherits:
Object
  • Object
show all
Defined in:
lib/csv_utils/csv_transformer.rb

Overview

Copies a CSV file through a pipeline of steps that filter, change and add to its rows in batches. Each step method returns the transformer so they can be chained, and #process runs them.

Step blocks receive the row, the headers as they were when the step was added, and the value computed by the last #additional_data step for the current batch.

Examples:

CSVUtils::CSVTransformer.new('input.csv', 'output.csv')
  .read_headers
  .select { |row, _headers, _data| row[0].to_i > 100 }
  .append(['Email']) { |row, _headers, _data| ["#{row[1].downcase}@example.com"] }
  .process

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(src_csv, dest_csv, csv_options = {}) ⇒ CSVTransformer

Returns a new instance of CSVTransformer.

Parameters:

  • src_csv (String, CSV, #shift) —

    path or CSV to read; paths are opened and closed by the transformer

  • dest_csv (String, CSV, #<<) —

    path or CSV to write

  • csv_options (Hash) (defaults to: {}) —

    options passed to CSV.open for paths; the source is read with its :encoding, 'bom|utf-8' by default, and the output written in the encoding values were decoded to (see EncodingOptions)



24
25
26
27
# File 'lib/csv_utils/csv_transformer.rb', line 24

def initialize(src_csv, dest_csv, csv_options = {})
  @src_csv = CSVUtils::CSVWrapper.new(src_csv, 'rb', EncodingOptions.read(csv_options))
  @dest_csv = CSVUtils::CSVWrapper.new(dest_csv, 'wb', EncodingOptions.write(csv_options))
end

Instance Attribute Details

#headers ⇒ Array<String>? (readonly)

Returns the headers the output will have after the steps added so far.

Returns:

  • (Array<String>, nil) —

    the headers the output will have after the steps added so far



18
19
20
# File 'lib/csv_utils/csv_transformer.rb', line 18

def headers
  @headers
end

Instance Method Details

#additional_data {|batch, headers| ... } ⇒ self

Computes a value once per batch, passed to the steps that follow as their third argument.

Yield Parameters:

  • batch (Array<Array<String>>)
  • headers (Array<String>, nil)

Returns:

  • (self)


40
41
42
43
# File 'lib/csv_utils/csv_transformer.rb', line 40

def additional_data(&block)
  steps << [:additional_data, @headers, block]
  self
end

#append(additional_headers) {|row, headers, additional_data| ... } ⇒ self

Adds the block's values to the end of each row.

Parameters:

  • additional_headers (Array<String>, nil) —

    headers for the new values; nil drops the header row

Yield Parameters:

  • row (Array<String>)
  • headers (Array<String>, nil)
  • additional_data (Object)

Yield Returns:

  • (Array) —

    values to append

Returns:

  • (self)


79
80
81
82
83
84
# File 'lib/csv_utils/csv_transformer.rb', line 79

def append(additional_headers, &block)
  steps << [:append, @headers, block]
  # without headers (read_headers not called) the output has no header row to extend
  @headers = (@headers + additional_headers if @headers && additional_headers)
  self
end

#each {|row, headers, additional_data| ... } ⇒ self

Calls the block for each row without changing it.

Yield Parameters:

  • row (Array<String>)
  • headers (Array<String>, nil)
  • additional_data (Object)

Returns:

  • (self)


89
90
91
92
# File 'lib/csv_utils/csv_transformer.rb', line 89

def each(&block)
  steps << [:each, @headers, block]
  self
end

#map(new_headers) {|row, headers, additional_data| ... } ⇒ self

Replaces each row with the block's result.

Parameters:

  • new_headers (Array<String>, nil) —

    the headers after this step

Yield Parameters:

  • row (Array<String>)
  • headers (Array<String>, nil)
  • additional_data (Object)

Yield Returns:

  • (Array) —

    the new row

Returns:

  • (self)


68
69
70
71
72
# File 'lib/csv_utils/csv_transformer.rb', line 68

def map(new_headers, &block)
  steps << [:map, @headers, block]
  @headers = new_headers
  self
end

#process(batch_size = 10_000) ⇒ void

This method returns an undefined value.

Runs the steps over every row, writes the output and closes the files it opened, even when a step raises.

Parameters:

  • batch_size (Integer) (defaults to: 10_000) —

    rows read and run through the steps at a time



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/csv_utils/csv_transformer.rb', line 105

def process(batch_size = 10_000)
  batch = []

  @dest_csv << @headers if @headers

  steps_proc = proc do
    steps.each do |step_type, current_headers, proc|
      batch = process_step(step_type, current_headers, batch, &proc)
    end

    batch.each { |row| @dest_csv << row }

    batch = []
  end

  while (row = @src_csv.shift)
    batch << row
    steps_proc.call if batch.size >= batch_size
  end

  steps_proc.call if batch.size.positive?
ensure
  @src_csv.close
  @dest_csv.close
end

#read_headers ⇒ self

Reads the first row as the headers. Without it, every row is data and the output has no header row.

Returns:

  • (self)


31
32
33
34
# File 'lib/csv_utils/csv_transformer.rb', line 31

def read_headers
  @headers = @src_csv.shift
  self
end

#reject {|row, headers, additional_data| ... } ⇒ self

Drops the rows the block returns true for.

Yield Parameters:

  • row (Array<String>)
  • headers (Array<String>, nil)
  • additional_data (Object)

Returns:

  • (self)


58
59
60
61
# File 'lib/csv_utils/csv_transformer.rb', line 58

def reject(&block)
  steps << [:reject, @headers, block]
  self
end

#select {|row, headers, additional_data| ... } ⇒ self

Keeps the rows the block returns true for.

Yield Parameters:

  • row (Array<String>)
  • headers (Array<String>, nil)
  • additional_data (Object)

Returns:

  • (self)


50
51
52
53
# File 'lib/csv_utils/csv_transformer.rb', line 50

def select(&block)
  steps << [:select, @headers, block]
  self
end

#set_headers(headers) ⇒ self

Replaces the headers written to the output.

Parameters:

  • headers (Array<String>, nil)

Returns:

  • (self)


97
98
99
100
# File 'lib/csv_utils/csv_transformer.rb', line 97

def set_headers(headers)
  @headers = headers
  self
end