2016-10-19 03:11:36 +00:00
|
|
|
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
|
2016-04-25 23:04:59 +00:00
|
|
|
|
|
|
|
class ExternalSync < ApplicationModel
|
|
|
|
store :last_payload
|
2017-03-09 10:32:05 +00:00
|
|
|
|
|
|
|
class << self
|
|
|
|
|
|
|
|
def changed?(object:, previous_changes: {}, current_changes:)
|
|
|
|
changed = false
|
|
|
|
previous_changes ||= {}
|
2017-10-01 12:25:52 +00:00
|
|
|
current_changes.each do |attribute, value|
|
2017-03-09 10:32:05 +00:00
|
|
|
next if !object.attributes.key?(attribute.to_s)
|
|
|
|
next if object[attribute] == value
|
|
|
|
next if object[attribute].present? && object[attribute] != previous_changes[attribute]
|
|
|
|
|
|
|
|
begin
|
|
|
|
object[attribute] = value
|
|
|
|
changed ||= true
|
|
|
|
rescue => e
|
|
|
|
Rails.logger.error "ERROR: Unable to assign attribute #{attribute} to object #{object.class.name}: #{e.inspect}"
|
|
|
|
end
|
2017-10-01 12:25:52 +00:00
|
|
|
end
|
2017-03-09 10:32:05 +00:00
|
|
|
changed
|
|
|
|
end
|
|
|
|
|
|
|
|
def map(mapping: {}, source:)
|
|
|
|
|
|
|
|
information_source = if source.is_a?(Hash)
|
|
|
|
source.deep_symbolize_keys
|
|
|
|
else
|
|
|
|
source.clone
|
|
|
|
end
|
|
|
|
|
|
|
|
result = {}
|
2017-10-01 12:25:52 +00:00
|
|
|
mapping.each do |remote_key, local_key|
|
2017-03-09 10:32:05 +00:00
|
|
|
|
|
|
|
local_key_sym = local_key.to_sym
|
|
|
|
|
|
|
|
next if result[local_key_sym].present?
|
|
|
|
value = extract(remote_key, information_source)
|
|
|
|
next if value.blank?
|
|
|
|
result[local_key_sym] = value
|
2017-10-01 12:25:52 +00:00
|
|
|
end
|
2017-03-09 10:32:05 +00:00
|
|
|
result
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def extract(remote_key, structure)
|
|
|
|
return if !structure
|
|
|
|
|
|
|
|
information_source = structure.clone
|
|
|
|
result = nil
|
|
|
|
information_path = remote_key.split('.')
|
|
|
|
information_path.each do |segment|
|
|
|
|
|
|
|
|
segment_sym = segment.to_sym
|
|
|
|
|
|
|
|
if information_source.is_a?(Hash)
|
|
|
|
value = information_source[segment_sym]
|
|
|
|
elsif information_source.respond_to?(segment_sym)
|
|
|
|
# prevent accessing non-attributes (e.g. destroy)
|
|
|
|
if information_source.respond_to?(:attributes)
|
|
|
|
break if !information_source.attributes.key?(segment)
|
|
|
|
end
|
|
|
|
value = information_source.send(segment_sym)
|
|
|
|
end
|
|
|
|
break if !value
|
|
|
|
|
|
|
|
storable = value.class.ancestors.any? do |ancestor|
|
2017-11-23 08:09:44 +00:00
|
|
|
%w[String Integer Float Bool Array].include?(ancestor.to_s)
|
2017-03-09 10:32:05 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
if storable
|
|
|
|
result = value
|
|
|
|
break
|
|
|
|
end
|
|
|
|
|
|
|
|
information_source = value
|
|
|
|
end
|
|
|
|
result
|
|
|
|
end
|
|
|
|
end
|
2016-04-25 23:04:59 +00:00
|
|
|
end
|