Class: CsvWizard::ImportJob

Inherits:
ActiveJob::Base
  • Object
show all
Defined in:
lib/csv_wizard/import_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(model_name, mappings, file_path, logger: nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/csv_wizard/import_job.rb', line 5

def perform(model_name, mappings, file_path, logger: nil)
  model = model_name.constantize
  mapper = Mapper.new
  mappings.each { |csv, attr| mapper.map(csv, to: attr) }

  importer = Object.new.extend(Importer)
  importer.instance_variable_set(:@mapper, mapper)
  importer.instance_variable_set(:@model_class, model)

  failed_rows = importer.import(file_path)

  # Conditional logger
  log =
    if logger
      logger
    elsif defined?(Rails) && Rails.respond_to?(:logger)
      Rails.logger
    else
      require "logging"
      Logging.logger['CsvWizard'].tap { |l| l.level = :info }
    end

  if failed_rows.any?
    log.error("[CSV Import] Errors: #{failed_rows.inspect}")
  else
    log.info("[CSV Import] Completed successfully.")
  end
end