Skip to content
This repository has been archived by the owner on Nov 23, 2021. It is now read-only.

Callbacks

Ernesto García edited this page Feb 14, 2014 · 2 revisions

An importer class can define blocks of code acting as callbacks, to be notified of certain events that occur while importing the data.

class EmployeeImporter < ActiveImporter::Base
  imports Employee

  attr_reader :row_count

  column 'First name'
  column 'Last name'
  column 'Department', :department do |department_name|
    Department.find_by(name: department_name)
  end

  on :row_processing do
    model.full_name = [row['First name'], row['Last name']].join(' ')
  end

  on :import_started do
    @row_count = 0
  end

  on :row_processed do
    @row_count += 1
  end

  on :import_finished do
    send_notification("Data imported successfully!")
  end

  on :import_failed do |exception|
    send_notification("Fatal error while importing data: #{exception.message}")
  end

  private

  def send_notification(message)
    # ...
  end
end

The supported events are:

  • import_failed: Fired once before the beginning of the data processing, if the input data cannot be processed for some reason. If this event is fired by an importer, none of its other events are ever fired.
  • import_started: Fired once at the beginning of the data processing, before the first row is processed.
  • row_processing: Fired while the row is being processed to be imported into a model instance.
  • row_skipped: Fired once for each row that matches the skip_rows_if condition, if any.
  • row_processed: Fired once for each row that has been processed, regardless of whether it resulted in success or error.
  • row_success: Fired once for each row that was imported successfully into the data model.
  • row_error: Fired once for each row that was not imported successfully into the data model.
  • import_finished: Fired once after all rows have been processed.
  • import_aborted: Fired once if the import process is aborted by invoking abort!.

More than one block of code can be provided for each of these events, and they will all be invoked in the same order in which they were declared. All blocks are executed in the context of the importer instance, so they have access to all the importer attributes and instance variables. Error-related events (:import_failed and :row_error) pass to the blocks the instance of the exception that provoked the error condition.

Additionally, all the row_* events have access to the row and model variables, which reference the spreadsheet row being processed, and the model object where the row data is being stored, respectively. This feature is particularly useful for the :row_processing event handler, which is triggered while a row is being processed, and before the corresponding data model is saved. This allows to define any complex data-import logic that cannot be expressed in terms of mapping a column to a data field.