attribute_validator.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class Validations::ObjectManager::AttributeValidator < ActiveModel::Validator
  3. include ::Mixin::HasBackends
  4. def validate(record)
  5. return if !validation_needed?
  6. @record = record
  7. sanitize_memory_cache
  8. return if attributes_unchanged?
  9. model_attributes.select(&:editable).each do |attribute|
  10. perform_validation(attribute)
  11. end
  12. end
  13. private
  14. attr_reader :record
  15. def validation_needed?
  16. return false if Setting.get('import_mode')
  17. return false if ApplicationHandleInfo.context_without_custom_attributes?
  18. ApplicationHandleInfo.current == 'application_server'
  19. end
  20. def attributes_unchanged?
  21. model_attributes.none? do |attribute|
  22. record.will_save_change_to_attribute?(attribute.name)
  23. end
  24. end
  25. def model_attributes
  26. @model_attributes ||= begin
  27. object_lookup_id = ObjectLookup.by_name(record.class.name)
  28. @active_attributes.select { |attribute| attribute.object_lookup_id == object_lookup_id }
  29. end
  30. end
  31. def perform_validation(attribute)
  32. backends.each do |backend|
  33. backend.validate(
  34. record: record,
  35. attribute: attribute
  36. )
  37. end
  38. end
  39. def sanitize_memory_cache
  40. @model_attributes = nil
  41. active_attributes = active_attributes_in_db
  42. latest_cache_key = active_attributes.cache_key + active_attributes.cache_version
  43. return if @previous_cache_key == latest_cache_key
  44. @previous_cache_key = latest_cache_key
  45. @active_attributes = active_attributes_in_db.to_a
  46. end
  47. def active_attributes_in_db
  48. ObjectManager::Attribute.where(active: true)
  49. end
  50. end