activemodel_error.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class ActiveModel::Error
  3. # Make it possible to retrieve errors that are translated with a Zammad locale.
  4. def localized_full_message(locale:, no_field_name: false)
  5. errors_hash = I18n.backend.translations[:en][:errors]
  6. orig_format = errors_hash[:format]
  7. errors_hash[:format] = Translation.translate(locale, 'This field %s', '%<message>s') if no_field_name
  8. I18n.with_zammad_locale(locale) do
  9. full_message
  10. end
  11. ensure
  12. errors_hash[:format] = orig_format
  13. end
  14. end
  15. module I18n
  16. def self.with_zammad_locale(locale)
  17. backend.zammad_locale = locale
  18. yield
  19. ensure
  20. backend.zammad_locale = nil
  21. end
  22. end
  23. class I18n::Backend::Simple
  24. attr_accessor :zammad_locale
  25. if !method_defined?(:orig_lookup)
  26. alias orig_lookup lookup
  27. # Allow I18n to load the default rails error messages from the YAML files,
  28. # but translate them to the target locale before the error messages get generated
  29. # including placeholder subsitition.
  30. def lookup(...)
  31. result = orig_lookup(...)
  32. if result.is_a?(String) && zammad_locale
  33. return Translation.translate(zammad_locale, result)
  34. end
  35. result
  36. end
  37. end
  38. end