notification_factory.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. class FileNotFoundError < StandardError; end
  25. def self.template_read(data)
  26. template_path = template_path(data)
  27. template = File.readlines(template_path)
  28. { subject: template.shift, body: template.join }
  29. end
  30. def self.template_path(data)
  31. candidates = template_filenames(data)
  32. .map { |filename| data.merge(filename: filename) }
  33. .map { |data_hash| TEMPLATE_PATH_STRING % data_hash }
  34. found = candidates.find(&File.method(:exist?))
  35. raise FileNotFoundError, "Missing template files #{candidates}!" if !found
  36. found
  37. end
  38. private_class_method :template_path
  39. def self.template_filenames(data)
  40. locale = data[:locale] || Locale.default
  41. [locale, locale[0, 2], 'en']
  42. .uniq
  43. .map { |locale_code| "#{locale_code}.#{data[:format]}.erb" }
  44. .map { |basename| ["#{basename}.custom", basename] }.flatten
  45. end
  46. private_class_method :template_filenames
  47. =begin
  48. string = NotificationFactory.application_template_read(
  49. format: 'html',
  50. type: 'mailer',
  51. )
  52. or
  53. string = NotificationFactory.application_template_read(
  54. format: 'md',
  55. type: 'slack',
  56. )
  57. returns
  58. 'some template'
  59. =end
  60. def self.application_template_read(data)
  61. File.read(APPLICATION_TEMPLATE_PATH_STRING % data)
  62. end
  63. end