external_sync.rb 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 "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. def migrate(object, from_id, to_id)
  38. where(
  39. object: object,
  40. o_id: from_id,
  41. ).update_all( # rubocop:disable Rails/SkipsModelValidations
  42. o_id: to_id,
  43. )
  44. end
  45. private
  46. def extract(remote_key, structure)
  47. return if !structure
  48. information_source = structure.clone
  49. result = nil
  50. information_path = remote_key.split('.')
  51. information_path.each do |segment|
  52. segment_sym = segment.to_sym
  53. if information_source.is_a?(Hash)
  54. value = information_source[segment_sym]
  55. elsif information_source.respond_to?(segment_sym)
  56. # prevent accessing non-attributes (e.g. destroy)
  57. if information_source.respond_to?(:attributes)
  58. break if !information_source.attributes.key?(segment)
  59. end
  60. value = information_source.send(segment_sym)
  61. end
  62. break if !value
  63. storable = value.class.ancestors.any? do |ancestor|
  64. %w[String Integer Float Bool Array].include?(ancestor.to_s)
  65. end
  66. if storable
  67. result = value
  68. break
  69. end
  70. information_source = value
  71. end
  72. result
  73. end
  74. end
  75. end