attributes.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Sequencer::Unit::Import::Common::Model::Lookup::Attributes < Sequencer::Unit::Base
  3. include ::Sequencer::Unit::Import::Common::Model::Mixin::HandleFailure
  4. prepend ::Sequencer::Unit::Import::Common::Model::Mixin::Skip::Action
  5. skip_action :skipped, :failed
  6. uses :mapped, :model_class
  7. provides :instance
  8. def process
  9. return if state.provided?(:instance)
  10. return if existing_instance.blank?
  11. state.provide(:instance, existing_instance)
  12. end
  13. private
  14. def attribute
  15. raise "Missing implementation of '#{__method__}' method for '#{self.class.name}'"
  16. end
  17. def attributes
  18. # alias or alias_method won't work if attribute method
  19. # is overwritten in inheriting sub-class
  20. attribute
  21. end
  22. def existing_instance
  23. @existing_instance ||= begin
  24. Array(attributes).find do |attribute|
  25. value = mapped[attribute]
  26. next if value.blank?
  27. existing_instance = lookup(
  28. attribute: attribute,
  29. value: value
  30. )
  31. next if existing_instance.blank?
  32. # https://stackoverflow.com/a/24901650/7900866
  33. break existing_instance
  34. end
  35. end
  36. end
  37. def lookup(attribute:, value:)
  38. return model_class.identify(value) if model_class.respond_to?(:identify)
  39. lookup_find_by(attribute, value)
  40. end
  41. def lookup_find_by(attribute, value)
  42. model_class.find_by(attribute => value)
  43. end
  44. end