Class: WorkerTools::CsvInput::CsvInputForeach

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/worker_tools/csv_input.rb

Instance Method Summary collapse

Constructor Details

#initialize(rows_enum:, input_columns:, mapping_order:, cleanup_method:, headers_present:) ⇒ CsvInputForeach

Returns a new instance of CsvInputForeach.



162
163
164
165
166
167
168
# File 'lib/worker_tools/csv_input.rb', line 162

def initialize(rows_enum:, input_columns:, mapping_order:, cleanup_method:, headers_present:)
  @rows_enum = rows_enum
  @input_columns = input_columns
  @mapping_order = mapping_order
  @cleanup_method = cleanup_method
  @headers_present = headers_present
end

Instance Method Details

#eachObject



170
171
172
173
174
175
176
177
178
# File 'lib/worker_tools/csv_input.rb', line 170

def each
  return enum_for(:each) unless block_given?

  @rows_enum.with_index.each do |values, index|
    next if index.zero? && @headers_present

    yield values_to_row(values)
  end
end

#values_to_row(values) ⇒ Object



180
181
182
183
184
# File 'lib/worker_tools/csv_input.rb', line 180

def values_to_row(values)
  return values_to_row_according_to_mapping(values) if @mapping_order

  values_to_row_according_to_position(values)
end

#values_to_row_according_to_mapping(values) ⇒ Object



186
187
188
189
190
# File 'lib/worker_tools/csv_input.rb', line 186

def values_to_row_according_to_mapping(values)
  @mapping_order.each_with_object(HashWithIndifferentAccess.new) do |(k, v), h|
    h[k] = @cleanup_method.call(values[v])
  end
end

#values_to_row_according_to_position(values) ⇒ Object



192
193
194
# File 'lib/worker_tools/csv_input.rb', line 192

def values_to_row_according_to_position(values)
  @input_columns.map.with_index { |c, i| [c, @cleanup_method.call(values[i])] }.to_h.with_indifferent_access
end