Added *args to pass optional data to import resources that get passed to internal methods an can help with customizations.

This commit is contained in:
Thorsten Eckel 2017-03-10 16:36:33 +01:00
parent 4448f8e0ca
commit c3a1ce393c

View file

@ -2,8 +2,8 @@ module Import
class BaseResource class BaseResource
include Import::Helper include Import::Helper
def initialize(resource) def initialize(resource, *args)
import(resource) import(resource, *args)
end end
def import_class def import_class
@ -14,23 +14,23 @@ module Import
raise "#{self.class.name} has no implmentation of the needed 'source' method" raise "#{self.class.name} has no implmentation of the needed 'source' method"
end end
def remote_id(resource) def remote_id(resource, *_args)
@remote_id ||= resource.delete(:id) @remote_id ||= resource.delete(:id)
end end
private private
def import(resource) def import(resource, *args)
create_or_update(map(resource)) create_or_update(map(resource, *args), *args)
end end
def create_or_update(resource) def create_or_update(resource, *args)
return if updated?(resource) return if updated?(resource, *args)
create(resource) create(resource, *args)
end end
def updated?(resource) def updated?(resource, *args)
@resource = lookup_existing(resource) @resource = lookup_existing(resource, *args)
return false if !@resource return false if !@resource
@resource.update_attributes(resource) @resource.update_attributes(resource)
post_update( post_update(
@ -40,7 +40,7 @@ module Import
true true
end end
def lookup_existing(resource) def lookup_existing(resource, *_args)
instance = ExternalSync.find_by( instance = ExternalSync.find_by(
source: source, source: source,
@ -51,7 +51,7 @@ module Import
import_class.find_by(id: instance.o_id) import_class.find_by(id: instance.o_id)
end end
def create(resource) def create(resource, *_args)
@resource = import_class.new(resource) @resource = import_class.new(resource)
@resource.save @resource.save
@ -68,21 +68,21 @@ module Import
) )
end end
def defaults(_resource) def defaults(_resource, *_args)
{ {
created_by_id: 1, created_by_id: 1,
updated_by_id: 1, updated_by_id: 1,
} }
end end
def map(resource) def map(resource, *args)
mapped = from_mapping(resource) mapped = from_mapping(resource, *args)
attributes = defaults(resource).merge(mapped) attributes = defaults(resource, *args).merge(mapped)
attributes.symbolize_keys attributes.symbolize_keys
end end
def from_mapping(resource) def from_mapping(resource, *args)
return resource if !mapping return resource if !mapping(*args)
ExternalSync.map( ExternalSync.map(
mapping: mapping, mapping: mapping,
@ -90,11 +90,11 @@ module Import
) )
end end
def mapping def mapping(*args)
Setting.get(mapping_config) Setting.get(mapping_config(*args))
end end
def mapping_config def mapping_config(*_args)
self.class.name.to_s.sub('Import::', '').gsub('::', '_').underscore + '_mapping' self.class.name.to_s.sub('Import::', '').gsub('::', '_').underscore + '_mapping'
end end