2018-04-26 08:55:53 +00:00
|
|
|
require_dependency 'sequencer/unit/import/common/model/mixin/handle_failure'
|
2017-08-14 11:56:23 +00:00
|
|
|
|
|
|
|
class Sequencer
|
|
|
|
class Unit
|
|
|
|
module Import
|
|
|
|
module Common
|
|
|
|
module Model
|
|
|
|
module Associations
|
|
|
|
class Assign < Sequencer::Unit::Base
|
|
|
|
include ::Sequencer::Unit::Import::Common::Model::Mixin::HandleFailure
|
|
|
|
|
2017-12-21 11:19:30 +00:00
|
|
|
uses :instance, :associations, :action, :dry_run
|
|
|
|
provides :action
|
2017-08-14 11:56:23 +00:00
|
|
|
|
|
|
|
def process
|
|
|
|
return if dry_run
|
|
|
|
return if instance.blank?
|
2018-07-18 09:29:44 +00:00
|
|
|
return if associations.blank? && log_associations_error
|
2017-08-14 11:56:23 +00:00
|
|
|
|
2018-07-18 09:29:44 +00:00
|
|
|
register_changes
|
2017-08-14 11:56:23 +00:00
|
|
|
instance.assign_attributes(associations)
|
|
|
|
rescue => e
|
|
|
|
handle_failure(e)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2018-07-18 09:29:44 +00:00
|
|
|
# always returns true
|
|
|
|
def log_associations_error
|
2018-10-10 06:23:45 +00:00
|
|
|
return true if %i[skipped failed deactivated].include?(action)
|
2018-10-09 06:17:41 +00:00
|
|
|
|
2018-07-18 09:29:44 +00:00
|
|
|
logger.error { 'associations cannot be nil' } if associations.nil?
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
def register_changes
|
|
|
|
return if !(action == :unchanged && changes.any?)
|
2018-10-09 06:17:41 +00:00
|
|
|
|
2018-03-20 17:47:49 +00:00
|
|
|
logger.debug { "Changed instance associations: #{changes.inspect}" }
|
2018-07-18 09:29:44 +00:00
|
|
|
state.provide(:action, :updated)
|
2017-08-14 11:56:23 +00:00
|
|
|
end
|
|
|
|
|
2018-07-18 09:29:44 +00:00
|
|
|
# Why not just use instance.changes?
|
|
|
|
# Because it doesn't include associations
|
|
|
|
# stored on OTHER TABLES (has-one, has-many, HABTM)
|
2017-08-14 11:56:23 +00:00
|
|
|
def changes
|
2018-07-18 09:29:44 +00:00
|
|
|
@changes ||= unfiltered_changes.reject(&method(:no_diff?))
|
|
|
|
end
|
|
|
|
|
|
|
|
def unfiltered_changes
|
|
|
|
attrs = associations.keys
|
|
|
|
before = attrs.map(&instance.method(:send))
|
|
|
|
after = associations.values
|
|
|
|
attrs.zip(before.zip(after)).to_h.with_indifferent_access
|
2017-08-14 11:56:23 +00:00
|
|
|
end
|
|
|
|
|
2018-07-18 09:29:44 +00:00
|
|
|
def no_diff?(_, values)
|
|
|
|
values.map!(&:sort) if values.all? { |val| val.respond_to?(:sort) }
|
|
|
|
values.map!(&:presence) # [nil, []] -> [nil, nil]
|
|
|
|
values.uniq.length == 1
|
2017-08-14 11:56:23 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|