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:
parent
63b0e4fe31
commit
4448f8e0ca
2 changed files with 45 additions and 13 deletions
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue