notification_factory.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. module NotificationFactory
  2. TEMPLATE_PATH_STRING = Rails.root.join('app', 'views', '%<type>s', '%<template>s', '%<filename>s').to_s.freeze
  3. APPLICATION_TEMPLATE_PATH_STRING = Rails.root.join('app', 'views', '%<type>s', 'application.%<format>s.erb').to_s.freeze
  4. =begin
  5. result = NotificationFactory.template_read(
  6. template: 'password_reset',
  7. locale: 'en-us',
  8. format: 'html',
  9. type: 'mailer',
  10. )
  11. or
  12. result = NotificationFactory.template_read(
  13. template: 'ticket_update',
  14. locale: 'en-us',
  15. format: 'md',
  16. type: 'slack',
  17. )
  18. returns
  19. {
  20. subject: 'some subject',
  21. body: 'some body',
  22. }
  23. =end
  24. def self.template_read(data)
  25. template = File.readlines(template_path(data))
  26. { subject: template.shift, body: template.join }
  27. end
  28. def self.template_path(data)
  29. template_filenames(data)
  30. .map { |filename| data.merge(filename: filename) }
  31. .map { |data_hash| TEMPLATE_PATH_STRING % data_hash }
  32. .find(&File.method(:exist?))
  33. end
  34. private_class_method :template_path
  35. def self.template_filenames(data)
  36. locale = data[:locale] || Setting.get('locale_default') || 'en-us'
  37. [locale, locale[0, 2], 'en']
  38. .uniq
  39. .map { |locale_code| "#{locale_code}.#{data[:format]}.erb" }
  40. .map { |basename| ["#{basename}.custom", basename] }.flatten
  41. end
  42. private_class_method :template_filenames
  43. =begin
  44. string = NotificationFactory.application_template_read(
  45. format: 'html',
  46. type: 'mailer',
  47. )
  48. or
  49. string = NotificationFactory.application_template_read(
  50. format: 'md',
  51. type: 'slack',
  52. )
  53. returns
  54. 'some template'
  55. =end
  56. def self.application_template_read(data)
  57. File.read(APPLICATION_TEMPLATE_PATH_STRING % data)
  58. end
  59. end