Class: BulkCsvParser::Processor

Inherits:
Object
  • Object
show all
Defined in:
lib/bulk_csv_parser/processor.rb

Overview

Generic, model-agnostic CSV importer/updater.

Streams the CSV row by row (CSV.foreach) so arbitrarily large files never get loaded into memory at once, batches rows, and either upserts them in bulk or finds/updates each record with full validation support.

Example:

BulkCsvParser::Processor.new(
file_path: "/tmp/users.csv",
model: User,
find_by: [:email],
attributes: [:first_name, :last_name, :status],
header_mapping: { "Email Address" => :email }
).call

Defined Under Namespace

Classes: ConfigurationError

Instance Method Summary collapse

Constructor Details

#initialize(model:, find_by:, attributes:, file_path: nil, file: nil, header_mapping: {}, batch_size: nil, strategy: nil, transform: nil, on_row_error: nil) ⇒ Processor

Returns a new instance of Processor.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/bulk_csv_parser/processor.rb', line 25

def initialize(
  model:,
  find_by:,
  attributes:,
  file_path: nil,
  file: nil,
  header_mapping: {},
  batch_size: nil,
  strategy: nil,
  transform: nil,
  on_row_error: nil
)
  @model = model.is_a?(String) ? model.constantize : model
  @file_path = file_path
  @file = file
  @find_by = Array(find_by).map(&:to_sym)
  @attributes = Array(attributes).map(&:to_sym)
  @header_mapping = header_mapping.each_with_object({}) { |(k, v), h| h[k.to_s] = v.to_sym }
  @batch_size = batch_size || BulkCsvParser.configuration.batch_size
  @strategy = (strategy || BulkCsvParser.configuration.strategy).to_sym
  @transform = transform
  @on_row_error = on_row_error
  @result = Result.new

  validate_arguments!
end

Instance Method Details

#callObject



52
53
54
55
56
57
58
59
# File 'lib/bulk_csv_parser/processor.rb', line 52

def call
  each_batch do |batch|
    next if batch.empty?

    strategy == :upsert ? process_upsert(batch) : process_save(batch)
  end
  result
end