From 4448f8e0ca31ee46d30f4392ac726156b31ec913 Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Fri, 10 Mar 2017 16:01:08 +0100 Subject: [PATCH] Extended the resource import functionality to use ExternalSync for remote and local ID mapping and lookup instead of attribute based relation. --- lib/import/base_resource.rb | 27 ++++++++++++++++++++++++-- spec/import/model_resource_spec.rb | 31 +++++++++++++++++++----------- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/lib/import/base_resource.rb b/lib/import/base_resource.rb index ebb8d6283..848e6e6bd 100644 --- a/lib/import/base_resource.rb +++ b/lib/import/base_resource.rb @@ -10,6 +10,14 @@ module Import raise "#{self.class.name} has no implmentation of the needed 'import_class' method" end + def source + raise "#{self.class.name} has no implmentation of the needed 'source' method" + end + + def remote_id(resource) + @remote_id ||= resource.delete(:id) + end + private def import(resource) @@ -33,12 +41,27 @@ module Import end def lookup_existing(resource) - import_class.find_by(name: resource[:name]) + + instance = ExternalSync.find_by( + source: source, + source_id: remote_id(resource), + object: import_class.name, + ) + return if !instance + import_class.find_by(id: instance.o_id) end def create(resource) @resource = import_class.new(resource) @resource.save + + ExternalSync.create( + source: source, + source_id: remote_id(resource), + object: import_class.name, + o_id: @resource.id + ) + post_create( instance: @resource, attributes: resource @@ -55,7 +78,7 @@ module Import def map(resource) mapped = from_mapping(resource) attributes = defaults(resource).merge(mapped) - attributes.deep_symbolize_keys + attributes.symbolize_keys end def from_mapping(resource) diff --git a/spec/import/model_resource_spec.rb b/spec/import/model_resource_spec.rb index 005ba864c..61d675977 100644 --- a/spec/import/model_resource_spec.rb +++ b/spec/import/model_resource_spec.rb @@ -6,15 +6,17 @@ RSpec.describe Import::ModelResource do module Import module Test class Group < Import::ModelResource + def source + 'RSpec-Test' + end end end end end + let(:group_data) { attributes_for(:group).merge(id: 1337) } + it 'creates model Objects by class name' do - - group_data = attributes_for(:group) - expect { Import::Test::Group.new(group_data) }.to change { Group.count }.by(1) @@ -22,14 +24,21 @@ RSpec.describe Import::ModelResource do it 'updates model Objects by class name' do - group = create(:group) + expect do + Import::Test::Group.new(group_data) + end + .to change { + Group.count + }.by(1) - update_attributes = group.serializable_hash - update_attributes[:note] = 'Updated' - - expect { - Import::Test::Group.new(update_attributes) - group.reload - }.to change { group.note } + expect do + Import::Test::Group.new(group_data.merge(note: 'Updated')) + end + .to change { + Group.count + }.by(0) + .and change { + Group.last.note + } end end