如何创建邮件观察者 [英] How do I create a Mailer Observer

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

问题描述

每当我的应用程序发送一封电子邮件时,我都希望运行一些代码.

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引入了Interceptor(在消息发送之前调用)和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).

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆