digest_email_agent.rb 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. module Agents
  2. class DigestEmailAgent < Agent
  3. MAIN_KEYS = %w[title message text main value].map(&:to_sym)
  4. default_schedule "5am"
  5. description <<-MD
  6. The DigestEmailAgent collects any Events sent to it and sends them all via email when run.
  7. The email will be sent to your account's address and will have a `subject` and an optional `headline` before
  8. listing the Events. If the Events' payloads contain a `:message`, that will be highlighted, otherwise everything in
  9. their payloads will be shown.
  10. Set `expected_receive_period_in_days` to the maximum amount of time that you'd expect to pass between Events being received by this Agent.
  11. MD
  12. def default_options
  13. {
  14. :subject => "You have some notifications!",
  15. :headline => "Your notifications:",
  16. :expected_receive_period_in_days => "2"
  17. }
  18. end
  19. def working?
  20. last_receive_at && last_receive_at > options[:expected_receive_period_in_days].to_i.days.ago
  21. end
  22. def validate_options
  23. errors.add(:base, "subject and expected_receive_period_in_days are required") unless options[:subject].present? && options[:expected_receive_period_in_days].present?
  24. end
  25. def receive(incoming_events)
  26. incoming_events.each do |event|
  27. self.memory[:queue] ||= []
  28. self.memory[:queue] << event.payload
  29. end
  30. end
  31. def check
  32. if self.memory[:queue] && self.memory[:queue].length > 0
  33. lines = self.memory[:queue].map {|item| present(item) }
  34. puts "Sending mail to #{user.email}..." unless Rails.env.test?
  35. SystemMailer.delay.send_message(:to => user.email, :subject => options[:subject], :headline => options[:headline], :lines => lines)
  36. self.memory[:queue] = []
  37. end
  38. end
  39. def present(item)
  40. if item.is_a?(Hash)
  41. MAIN_KEYS.each do |key|
  42. if item.has_key?(key)
  43. return "#{item[key]}" + ((item.length > 1 && item.length < 5) ? " (#{present_hash item, key})" : "")
  44. elsif item.has_key?(key.to_s)
  45. return "#{item[key.to_s]}" + ((item.length > 1 && item.length < 5) ? " (#{present_hash item, key.to_s})" : "")
  46. end
  47. end
  48. present_hash item
  49. else
  50. item.to_s
  51. end
  52. end
  53. def present_hash(hash, skip_key = nil)
  54. hash.to_a.sort_by {|a| a.first.to_s }.map { |k, v| "#{k}: #{v}" unless [skip_key].include?(k) }.compact.to_sentence
  55. end
  56. end
  57. end