external_sync.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class ExternalSync < ApplicationModel
  3. store :last_payload
  4. class << self
  5. def changed?(object:, previous_changes: {}, current_changes:)
  6. changed = false
  7. previous_changes ||= {}
  8. current_changes.each do |attribute, value|
  9. next if !object.attributes.key?(attribute.to_s)
  10. next if object[attribute] == value
  11. next if object[attribute].present? && object[attribute] != previous_changes[attribute]
  12. begin
  13. object[attribute] = value
  14. changed ||= true
  15. rescue => e
  16. Rails.logger.error "ERROR: Unable to assign attribute #{attribute} to object #{object.class.name}: #{e.inspect}"
  17. end
  18. end
  19. changed
  20. end
  21. def map(mapping: {}, source:)
  22. information_source = if source.is_a?(Hash)
  23. source.deep_symbolize_keys
  24. else
  25. source.clone
  26. end
  27. result = {}
  28. mapping.each do |remote_key, local_key|
  29. local_key_sym = local_key.to_sym
  30. next if result[local_key_sym].present?
  31. value = extract(remote_key, information_source)
  32. next if value.blank?
  33. result[local_key_sym] = value
  34. end
  35. result
  36. end
  37. private
  38. def extract(remote_key, structure)
  39. return if !structure
  40. information_source = structure.clone
  41. result = nil
  42. information_path = remote_key.split('.')
  43. information_path.each do |segment|
  44. segment_sym = segment.to_sym
  45. if information_source.is_a?(Hash)
  46. value = information_source[segment_sym]
  47. elsif information_source.respond_to?(segment_sym)
  48. # prevent accessing non-attributes (e.g. destroy)
  49. if information_source.respond_to?(:attributes)
  50. break if !information_source.attributes.key?(segment)
  51. end
  52. value = information_source.send(segment_sym)
  53. end
  54. break if !value
  55. storable = value.class.ancestors.any? do |ancestor|
  56. %w[String Integer Float Bool Array].include?(ancestor.to_s)
  57. end
  58. if storable
  59. result = value
  60. break
  61. end
  62. information_source = value
  63. end
  64. result
  65. end
  66. end
  67. end