Ruby on rails 如何拦截ActionMailer';rails 3上的消息是什么?

Ruby on rails 如何拦截ActionMailer';rails 3上的消息是什么?,ruby-on-rails,ruby-on-rails-3,actionmailer,Ruby On Rails,Ruby On Rails 3,Actionmailer,我正在尝试截取rails(3.0.10)应用程序中的消息以修改正文。虽然我能够找到一些关于如何做到这一点的信息,但似乎有些事情已经改变,现在使用旧方法不再有效 我使用的代码如下所示: class Hook def self.delivering_email(message) message.subject = 'Hook changed the subject' end end ActionMailer::Base.register_interceptor(Hook) 发送电

我正在尝试截取rails(3.0.10)应用程序中的消息以修改正文。虽然我能够找到一些关于如何做到这一点的信息,但似乎有些事情已经改变,现在使用旧方法不再有效

我使用的代码如下所示:

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

ActionMailer::Base.register_interceptor(Hook)
发送电子邮件后,主题不会改变

我还发现,这表明在消息上使用
deliver
方法时不会调用拦截器,但是gem使用了与我使用的方法相同的方法,并且它在那里工作(插件特别提到它与
deliver
方法一起工作)


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

听起来可能是操作顺序问题

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


如果premailer插件工作正常,我能想到的唯一区别就是在应用程序初始化过程中注册拦截挂钩的时间。

请参阅RailsCast或AsciCast插曲#206

第一集的相关部分,

/lib/development\u mail\u interceptor.rb

class DevelopmentMailInterceptor
  def self.delivering_email(message)
    message.subject = "[#{message.to}] #{message.subject}"
    message.to = "eifion@asciicasts.com"
  end
end
Mail.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?
/config/initializers/setup\u mail.rb

class DevelopmentMailInterceptor
  def self.delivering_email(message)
    message.subject = "[#{message.to}] #{message.subject}"
    message.to = "eifion@asciicasts.com"
  end
end
Mail.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?

您的
Hook
类在哪里定义,您从哪里调用
register\u interceptor
方法?它在
lib
dir的文件中。类定义之后立即调用
寄存器\u拦截器。我使用初始值设定项加载所有LIB。我还通过创建一个未定义的类来确保它被加载,并且rails告诉了我关于它的足够多的信息,所以我确信它被加载了。你是否尝试过在你的
delivery\u email
方法中放入一个logger语句来确保它被调用?是的,我尝试过,但它没有被调用。这证实了我上面提到的tweet,但是它在premailer gem中是如何工作的呢?你的代码对我来说非常好。我建议发布包含此代码的
lib
文件的代码,以及发布需要此lib文件的代码。