Class: Zizia::Importer

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/zizia/importer.rb

Overview

The chief entry point for bulk import of records. `Importer` accepts a Parser on initialization and iterates through its Parser#records, importing each using a given RecordImporter.

Examples:

Importing in bulk from a CSV file

parser = Zizia::Parser.for(file: File.new('path/to/import.csv'))

Zizia::Importer.new(parser: parser).import if parser.validate

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parser:, record_importer: RecordImporter.new) ⇒ Importer

Returns a new instance of Importer.

Parameters:

  • parser (Parser)

    The parser to use as the source for import records.

  • record_importer (RecordImporter) (defaults to: RecordImporter.new)

    An object to handle import of each record


34
35
36
37
# File 'lib/zizia/importer.rb', line 34

def initialize(parser:, record_importer: RecordImporter.new)
  self.parser          = parser
  self.record_importer = record_importer
end

Instance Attribute Details

#parserParser

Returns:


22
23
24
# File 'lib/zizia/importer.rb', line 22

def parser
  @parser
end

#record_importerRecordImporter

Returns:


22
# File 'lib/zizia/importer.rb', line 22

attr_accessor :parser, :record_importer

Instance Method Details

#importvoid

This method returns an undefined value.

Import each record in #records.


48
49
50
51
52
53
54
55
56
# File 'lib/zizia/importer.rb', line 48

def import
  no_records_message && return unless records.count.positive?
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  Rails.logger.info "[zizia] event: start_import, batch_id: #{record_importer.batch_id}, expecting to import #{records.count} records."
  records.each { |record| record_importer.import(record: record) }
  end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  elapsed_time = end_time - start_time
  Rails.logger.info "[zizia] event: finish_import, batch_id: #{record_importer.batch_id}, successful_record_count: #{record_importer.success_count}, failed_record_count: #{record_importer.failure_count}, elapsed_time: #{elapsed_time}, elapsed_time_per_record: #{elapsed_time / records.count}"
end

#no_records_messageObject

Do not attempt to run an import if there are no records. Instead, just write to the log.


40
41
42
# File 'lib/zizia/importer.rb', line 40

def no_records_message
  Rails.logger.error "[zizia] event: empty_import, batch_id: #{record_importer.batch_id}"
end

#recordsObject

See Also:


27
# File 'lib/zizia/importer.rb', line 27

def_delegator :parser, :records, :records