notification_factory.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. class String
  2. def message_quote
  3. quote = self.split("\n")
  4. body_quote = ''
  5. quote.each do |line|
  6. body_quote = body_quote + '> ' + line + "\n"
  7. end
  8. body_quote
  9. end
  10. def word_wrap(*args)
  11. options = args.extract_options!
  12. unless args.blank?
  13. options[:line_width] = args[0] || 82
  14. end
  15. options.reverse_merge!(:line_width => 82)
  16. lines = self
  17. lines.split("\n").collect do |line|
  18. line.length > options[:line_width] ? line.gsub(/(.{1,#{options[:line_width]}})(\s+|$)/, "\\1\n").strip : line
  19. end * "\n"
  20. end
  21. end
  22. module NotificationFactory
  23. def self.build(data)
  24. data[:string].gsub!( /\#\{(.+?)\}/ ) { |s|
  25. # use quoted text
  26. callback = $1
  27. callback.gsub!( /\.body$/ ) { |item|
  28. item = item + '.word_wrap( :line_width => 82 ).message_quote.chomp'
  29. }
  30. # use config params
  31. callback.gsub!( /^config\.(.+?)$/ ) { |item|
  32. name = $1
  33. item = "Setting.get('#{$1}')"
  34. }
  35. # use object params
  36. callback.gsub!( /^(.+?)(\..+?)$/ ) { |item|
  37. object_name = $1
  38. object_method = $2
  39. replace = nil
  40. if data[:objects][object_name.to_sym]
  41. replace = "data[:objects]['#{object_name}'.to_sym]#{object_method}"
  42. else
  43. replace = $1 + $2
  44. end
  45. item = replace
  46. }
  47. # replace value
  48. begin
  49. s = eval callback
  50. rescue Exception => e
  51. Rails.logger.error "can't eval #{callback}"
  52. Rails.logger.error e.inspect
  53. end
  54. }
  55. return data[:string]
  56. end
  57. def self.send(data)
  58. sender = Setting.get('notification_sender')
  59. a = Channel::IMAP.new
  60. Rails.logger.info "NOTICE: SEND NOTIFICATION TO: #{data[:recipient][:email]}"
  61. message = a.send(
  62. {
  63. # :in_reply_to => self.in_reply_to,
  64. :from => sender,
  65. :to => data[:recipient][:email],
  66. :subject => data[:subject],
  67. :body => data[:body],
  68. },
  69. true
  70. )
  71. end
  72. end