class Sp2db::ImportStrategy::Base

Attributes

result[RW]
rows[RW]
table[RW]

Public Class Methods

new(table, rows) click to toggle source
# File lib/sp2db/import_strategy.rb, line 41
def initialize table, rows
  self.table = table
  self.rows = rows
end

Public Instance Methods

after_import() click to toggle source
# File lib/sp2db/import_strategy.rb, line 92
def after_import
  logger.debug "Run after import table: #{self.table.name}"
end
before_import() click to toggle source
# File lib/sp2db/import_strategy.rb, line 61
def before_import
  logger.debug "Run before import table: #{self.table.name}"
end
errors() click to toggle source
# File lib/sp2db/import_strategy.rb, line 53
def errors
  result[:errors]
end
find_db_row(row) click to toggle source
# File lib/sp2db/import_strategy.rb, line 65
def find_db_row row
  if find_columns.present?
    cond = {}
    find_columns.each do |col|
      cond[col] = row[col]
    end
    model.find_by cond
  else
    nil # nil to skip
  end
end
import() click to toggle source
# File lib/sp2db/import_strategy.rb, line 96
def import
  logger.debug "Start import table: #{self.table.name}"
  ActiveRecord::Base.transaction(requires_new: true) do
    before_import
    rows.each do |row|
      row = row.clone
      begin
        table.before_import_row row
        record = import_row row
        records << record
        table.after_import_row record
      rescue ActiveRecord::ActiveRecordError => e
        logger.error e.try(:message)
        errors << {
          message: e.try(:message),
          exception: e,
          row: row,
          table: table.name,
        }
        next unless ExceptionHandler.row_import_error e
      end
    end
    after_import
    table.after_import_table result
    logger.debug "Import finished: #{self.table.name}"
    return result
  end

end
import_row(row) click to toggle source
# File lib/sp2db/import_strategy.rb, line 84
def import_row row
  record = find_db_row(row) || model.new(row)
  record = set_record_value record, row
  return unless record.present?
  record.save! if record.new_record? || record.changed?
  record
end
records() click to toggle source
# File lib/sp2db/import_strategy.rb, line 57
def records
  result[:records]
end
set_record_value(record, row) click to toggle source
# File lib/sp2db/import_strategy.rb, line 77
def set_record_value record, row
  row.each do |k, v|
    record.send("#{k}=", v) if record.respond_to?("#{k}=")
  end
  record
end