Improved association change tracking for broader use cases.

This commit is contained in:
Thorsten Eckel 2017-04-27 10:46:49 +02:00
parent 508415898f
commit aa53c4e697
2 changed files with 24 additions and 6 deletions

View file

@ -6,7 +6,10 @@ module Import
def initialize(resource, *args) def initialize(resource, *args)
handle_args(resource, *args) handle_args(resource, *args)
initialize_associations_states
import(resource, *args) import(resource, *args)
return if @resource.blank?
store_associations(:after, @resource)
end end
def import_class def import_class
@ -30,8 +33,7 @@ module Import
end end
def attributes_changed? def attributes_changed?
return true if changed_attributes.present? changed_attributes.present? || changed_associations.present?
@associations_init != associations_state(@resource)
end end
def changed_attributes def changed_attributes
@ -42,6 +44,15 @@ module Import
@resource.previous_changes @resource.previous_changes
end end
def changed_associations
changes = {}
tracked_associations.each do |association|
next if @associations[:before][association] == @associations[:after][association]
changes[association] = [@associations[:before][association], @associations[:after][association]]
end
changes
end
def created? def created?
return false if @resource.blank? return false if @resource.blank?
# dry run # dry run
@ -52,6 +63,13 @@ module Import
private private
def initialize_associations_states
@associations = {}
%i(before after).each do |state|
@associations[state] ||= {}
end
end
def import(resource, *args) def import(resource, *args)
create_or_update(map(resource, *args), *args) create_or_update(map(resource, *args), *args)
rescue => e rescue => e
@ -96,13 +114,13 @@ module Import
return if !synced_instance return if !synced_instance
instance = import_class.find_by(id: synced_instance.o_id) instance = import_class.find_by(id: synced_instance.o_id)
store_associations_state(instance) store_associations(:before, instance)
instance instance
end end
def store_associations_state(instance) def store_associations(state, instance)
@associations_init = associations_state(instance) @associations[state] = associations_state(instance)
end end
def associations_state(instance) def associations_state(instance)

View file

@ -94,7 +94,7 @@ module Import
remote: resource, remote: resource,
) )
store_associations_state(instance) store_associations(:before, instance)
end end
instance instance