email_concern.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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(:base, "subject and expected_receive_period_in_days are required") unless options['subject'].present? && options['expected_receive_period_in_days'].present?
  9. if options['recipients'].present?
  10. emails = options['recipients']
  11. emails = [emails] if emails.is_a?(String)
  12. unless emails.all? { |email| email =~ Devise.email_regexp || email =~ /\{/ }
  13. errors.add(:base, "'when provided, 'recipients' should be an email address or an array of email addresses")
  14. end
  15. end
  16. end
  17. def recipients(payload = {})
  18. emails = interpolated(payload)['recipients']
  19. if emails.present?
  20. if emails.is_a?(String)
  21. [emails]
  22. else
  23. emails
  24. end
  25. else
  26. [user.email]
  27. end
  28. end
  29. def working?
  30. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  31. end
  32. def present(payload)
  33. if payload.is_a?(Hash)
  34. payload = ActiveSupport::HashWithIndifferentAccess.new(payload)
  35. MAIN_KEYS.each do |key|
  36. return { :title => payload[key].to_s, :entries => present_hash(payload, key) } if payload.has_key?(key)
  37. end
  38. { :title => "Event", :entries => present_hash(payload) }
  39. else
  40. { :title => payload.to_s, :entries => [] }
  41. end
  42. end
  43. def present_hash(hash, skip_key = nil)
  44. hash.to_a.sort_by {|a| a.first.to_s }.map { |k, v| "#{k}: #{v}" unless k.to_s == skip_key.to_s }.compact
  45. end
  46. end