Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

ruby on rails 3 - How do I create a Mailer Observer

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

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

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)

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.

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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...