本文介绍了我如何创建邮件观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当在我的应用上发送电子邮件时,我都想运行一些代码.

I'd like to run some code whenever an email is sent on my app.

由于 ActionMailer 不支持 after_filter,我想使用观察者.

As ActionMailer doesn't support after_filter, I would like to use an observer.

Rails 文档顺便提到了这一点,但没有详细说明.

The Rails docs mention this in passing, however does not elaborate.

谢谢!

推荐答案

我很惊讶 Rails 的文档中很少有这方面的内容.

I'm surprised how little there is in Rails' documentation about this.

基本上,Rails 3 中的 ActionMailer 引入了 Interceptors(在发送消息之前调用)和 Observers(在发送消息之后)的使用.

Basically, ActionMailer in Rails 3 introduces the use of Interceptors (called before the message is sent) and Observers (after the message is sent).

要设置观察者,请将以下内容添加到初始值设定项:

To set up an Observer, add the following to an initializer:

class MailObserver
  def self.delivered_email(message)
    # Do whatever you want with the message in here
  end
end

ActionMailer::Base.register_observer(MailObserver)

现在,每次您的应用发送电子邮件时,delivered_email 方法都会运行.但是,您只能访问实际的Mail 消息.

Now, the delivered_email method will run every time your app sends an e-mail. However, you will only have access to the actual Mail message.

要注册一个拦截器,与上述相同,将register_observer替换为register_interceptor,并将方法从self.delivered_email重命名为self.delivering_email.

To register an Interceptor instead, do the same as above, replacing register_observer with register_interceptor, and renaming the method from self.delivered_email to self.delivering_email.

这个 Railscast 是我能找到的最好的资源关于这个的信息(他们只讨论拦截器,但观察者的概念是一样的).

This Railscast was the best source I could find for info on this (they only talk about interceptors, but the concept is the same for observers).

这篇关于我如何创建邮件观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:10