notification_factory.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. # translate
  56. data[:string].gsub!( /i18n\((.+?)\)/ ) { |s|
  57. string = $1
  58. locale = data[:locale] || 'en'
  59. s = Translation.translate( locale, string )
  60. }
  61. return data[:string]
  62. end
  63. def self.send(data)
  64. sender = Setting.get('notification_sender')
  65. a = Channel::IMAP.new
  66. Rails.logger.info "NOTICE: SEND NOTIFICATION TO: #{data[:recipient][:email]}"
  67. message = a.send(
  68. {
  69. # :in_reply_to => self.in_reply_to,
  70. :from => sender,
  71. :to => data[:recipient][:email],
  72. :subject => data[:subject],
  73. :body => data[:body],
  74. },
  75. true
  76. )
  77. end
  78. end