如何在rails 3上拦截ActionMailer的消息?

Mah*_*ver 3 ruby-on-rails actionmailer ruby-on-rails-3

我试图拦截我的rails(3.0.10)应用程序中的消息来修改正文.虽然我能够找到一些关于如何做到这一点的信息,但似乎已经发生了变化,现在使用旧方法已经不再适用了.

我使用的代码如下所示:

class Hook
  def self.delivering_email(message)
    message.subject = 'Hook changed the subject'
  end
end

ActionMailer::Base.register_interceptor(Hook)
Run Code Online (Sandbox Code Playgroud)

发送电子邮件后,主题不会更改!

我还发现了一条推文,指出deliver在消息上使用方法时没有调用拦截器,但是premailer-rails3 gem使用了我使用的相同方法并且它在那里工作(该插件特别提到它适用于该deliver方法)!

我在这里没有想法,所以是什么导致了我的问题?

Win*_*eld 5

听起来这可能是一个操作顺序问题.

您是否考虑过将您引用的整个代码块放在初始化程序中config/initializers/mail_hook.rb

如果该预备件插件工作,我能想到的唯一区别是在应用程序初始化过程中注册了拦截钩子.


小智 5

请参阅RailsCast或AsciiCast第206集

http://railscasts.com/episodes/206-action-mailer-in-rails-3

http://asciicasts.com/episodes/206-action-mailer-in-rails-3

第一集的相关部分,

/lib/development_mail_interceptor.rb

class DevelopmentMailInterceptor
  def self.delivering_email(message)
    message.subject = "[#{message.to}] #{message.subject}"
    message.to = "eifion@asciicasts.com"
  end
end
Run Code Online (Sandbox Code Playgroud)

/config/initializers/setup_mail.rb

Mail.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?
Run Code Online (Sandbox Code Playgroud)