20240618081710_migrate_template_options.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class MigrateTemplateOptions < ActiveRecord::Migration[7.0]
  3. def change
  4. # return if it's a new setup
  5. return if !Setting.exists?(name: 'system_init_done')
  6. Template.all.each do |template|
  7. if old_options?(template.options)
  8. template.options = migrate_options(template.options)
  9. template.save!
  10. end
  11. end
  12. end
  13. def old_options?(options)
  14. options.each_key do |key|
  15. return false if key.starts_with?(%r{(ticket|article)\.})
  16. end
  17. true
  18. end
  19. # Implements a compatibility layer for templates, by converting `options` to a newer format:
  20. # options: {
  21. # 'ticket.field_1': { value: 'value_1' },
  22. # 'ticket.field_2': { value: 'value_2', value_completion: 'value_completion_2' },
  23. # }
  24. def migrate_options(options)
  25. old_options = options.clone
  26. new_options = {}
  27. article_attribute_list = %w[body form_id]
  28. old_options.each do |key, value|
  29. new_key = "ticket.#{key}"
  30. if article_attribute_list.include?(key)
  31. new_key = "article.#{key}"
  32. end
  33. new_options[new_key] = { value: value }
  34. if old_options.key?("#{key}_completion")
  35. new_options[new_key]['value_completion'] = old_options["#{key}_completion"]
  36. old_options.delete("#{key}_completion")
  37. end
  38. end
  39. new_options
  40. end
  41. end