email_concern.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. module EmailConcern
  2. extend ActiveSupport::Concern
  3. MAIN_KEYS = %w[title message text main value]
  4. included do
  5. self.validate :validate_email_options
  6. end
  7. def validate_email_options
  8. errors.add(
  9. :base,
  10. "subject and expected_receive_period_in_days are required"
  11. ) unless options['subject'].present? && options['expected_receive_period_in_days'].present?
  12. if options['recipients'].present?
  13. emails = options['recipients']
  14. emails = [emails] if emails.is_a?(String)
  15. unless emails.all? { |email| Devise.email_regexp === email || /\{/ === email }
  16. errors.add(:base, "'when provided, 'recipients' should be an email address or an array of email addresses")
  17. end
  18. end
  19. end
  20. def recipients(payload = {})
  21. emails = interpolated(payload)['recipients']
  22. if emails.present?
  23. if emails.is_a?(String)
  24. [emails]
  25. else
  26. emails
  27. end
  28. else
  29. [user.email]
  30. end
  31. end
  32. def working?
  33. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  34. end
  35. def present(payload)
  36. if payload.is_a?(Hash)
  37. payload = ActiveSupport::HashWithIndifferentAccess.new(payload)
  38. MAIN_KEYS.each do |key|
  39. return { title: payload[key].to_s, entries: present_hash(payload, key) } if payload.has_key?(key)
  40. end
  41. { title: "Event", entries: present_hash(payload) }
  42. else
  43. { title: payload.to_s, entries: [] }
  44. end
  45. end
  46. def present_hash(hash, skip_key = nil)
  47. hash.to_a.sort_by { |a| a.first.to_s }.map { |k, v| "#{k}: #{v}" unless k.to_s == skip_key.to_s }.compact
  48. end
  49. end