Extended the resource import functionality to use ExternalSync for remote and local ID mapping and lookup instead of attribute based relation.

This commit is contained in:
Thorsten Eckel 2017-03-10 16:01:08 +01:00
parent 63b0e4fe31
commit 4448f8e0ca
2 changed files with 45 additions and 13 deletions

View file

@ -10,6 +10,14 @@ module Import
raise "#{self.class.name} has no implmentation of the needed 'import_class' method" raise "#{self.class.name} has no implmentation of the needed 'import_class' method"
end 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 private
def import(resource) def import(resource)
@ -33,12 +41,27 @@ module Import
end end
def lookup_existing(resource) 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 end
def create(resource) def create(resource)
@resource = import_class.new(resource) @resource = import_class.new(resource)
@resource.save @resource.save
ExternalSync.create(
source: source,
source_id: remote_id(resource),
object: import_class.name,
o_id: @resource.id
)
post_create( post_create(
instance: @resource, instance: @resource,
attributes: resource attributes: resource
@ -55,7 +78,7 @@ module Import
def map(resource) def map(resource)
mapped = from_mapping(resource) mapped = from_mapping(resource)
attributes = defaults(resource).merge(mapped) attributes = defaults(resource).merge(mapped)
attributes.deep_symbolize_keys attributes.symbolize_keys
end end
def from_mapping(resource) def from_mapping(resource)

View file

@ -6,15 +6,17 @@ RSpec.describe Import::ModelResource do
module Import module Import
module Test module Test
class Group < Import::ModelResource class Group < Import::ModelResource
def source
'RSpec-Test'
end end
end end
end end
end end
end
let(:group_data) { attributes_for(:group).merge(id: 1337) }
it 'creates model Objects by class name' do it 'creates model Objects by class name' do
group_data = attributes_for(:group)
expect { expect {
Import::Test::Group.new(group_data) Import::Test::Group.new(group_data)
}.to change { Group.count }.by(1) }.to change { Group.count }.by(1)
@ -22,14 +24,21 @@ RSpec.describe Import::ModelResource do
it 'updates model Objects by class name' 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 expect do
update_attributes[:note] = 'Updated' Import::Test::Group.new(group_data.merge(note: 'Updated'))
end
expect { .to change {
Import::Test::Group.new(update_attributes) Group.count
group.reload }.by(0)
}.to change { group.note } .and change {
Group.last.note
}
end end
end end