extract.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Sequencer::Unit::Import::Common::Model::Associations::Extract < Sequencer::Unit::Base
  3. prepend ::Sequencer::Unit::Import::Common::Model::Mixin::Skip::Action
  4. skip_any_action
  5. uses :model_class, :mapped
  6. provides :associations
  7. def process
  8. state.provide(:associations) do
  9. associations.filter_map do |association|
  10. logger.debug { "Checking association '#{association}'" }
  11. next if !mapped.key?(association)
  12. # remove from the mapped values if it's an association
  13. value = mapped.delete(association)
  14. logger.debug { "Extracted association '#{association}' value '#{value.inspect}'" }
  15. # skip if we don't track them
  16. next if tracked_associations.exclude?(association)
  17. logger.debug { "Using value of association '#{association}'" }
  18. [association, value]
  19. end.to_h
  20. end
  21. end
  22. private
  23. def associations
  24. @associations ||= begin
  25. # loop over all reflections
  26. model_class.reflect_on_all_associations.each_with_object([]) do |reflection, associations|
  27. # refection name is something like groups or organization (singular/plural)
  28. associations.push(reflection.name)
  29. # key is something like group_id or organization_id (singular)
  30. key = reflection.klass.name.foreign_key
  31. # add trailing 's' to get pluralized key
  32. reflection_name = reflection.name.to_s
  33. if reflection_name.singularize != reflection_name
  34. key = "#{key}s"
  35. end
  36. # store _id/_ids name
  37. associations.push(key.to_sym)
  38. end
  39. end
  40. end
  41. def tracked_associations
  42. # track all associations by default
  43. associations
  44. end
  45. end