notification_factory.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module NotificationFactory
  3. TEMPLATE_PATH_STRING = Rails.root.join('app/views/%{type}/%{template}/%{filename}').to_s.freeze
  4. APPLICATION_TEMPLATE_PATH_STRING = Rails.root.join('app/views/%{type}/application.%{format}.erb').to_s.freeze
  5. =begin
  6. result = NotificationFactory.template_read(
  7. template: 'password_reset',
  8. locale: 'en-us',
  9. format: 'html',
  10. type: 'mailer',
  11. )
  12. or
  13. result = NotificationFactory.template_read(
  14. template: 'ticket_update',
  15. locale: 'en-us',
  16. format: 'md',
  17. type: 'messaging',
  18. )
  19. returns
  20. {
  21. subject: 'some subject',
  22. body: 'some body',
  23. }
  24. =end
  25. class FileNotFoundError < StandardError; end
  26. def self.template_read(data)
  27. template_path = template_path(data)
  28. template = File.readlines(template_path)
  29. { subject: template.shift, body: template.join }
  30. end
  31. def self.template_path(data)
  32. candidates = template_filenames(data)
  33. .map { |filename| data.merge(filename: filename) }
  34. .map { |data_hash| TEMPLATE_PATH_STRING % data_hash }
  35. found = candidates.find { |candidate| File.exist?(candidate) }
  36. raise FileNotFoundError, "Missing template files #{candidates}!" if !found
  37. found
  38. end
  39. private_class_method :template_path
  40. def self.template_filenames(data)
  41. locale = data[:locale] || Locale.default
  42. [locale, locale[0, 2], 'en']
  43. .uniq
  44. .map { |locale_code| "#{locale_code}.#{data[:format]}.erb" }
  45. .map { |basename| ["#{basename}.custom", basename] }.flatten
  46. end
  47. private_class_method :template_filenames
  48. =begin
  49. string = NotificationFactory.application_template_read(
  50. format: 'html',
  51. type: 'mailer',
  52. )
  53. or
  54. string = NotificationFactory.application_template_read(
  55. format: 'md',
  56. type: 'messaging',
  57. )
  58. returns
  59. 'some template'
  60. =end
  61. def self.application_template_read(data)
  62. File.read(APPLICATION_TEMPLATE_PATH_STRING % data)
  63. end
  64. end