Rails 4.0 先睹为快:异步 ActionMailer(Rails 4.0 Sneak Peek: Asynchronous ActionMailer)

By | 2018年7月12日

My previous deep dive into the Rails 4.0 Queueing system was motivated by a patch to Rails I was working on while at RailsCamp New England this past weekend. I’m happy to say that Rails 4.0 now has an optional asynchronous ActionMailer.

The API for pushing your emails to the background is very simple. If you want to make this change application wide simply set it in yourapplication.rb(or in any of the environment files)

config.action_mailer.async = true

Or if you want to only make specific mailers asynchrounous

class WelcomeMailer < ActionMailer::Base
  self.async = true
end

That’s it! Any messages that are being delivered will be sent as a background job. In fact, the rendering is happening on the background as well.

你可能还需要关心传递给 mailer 的参数是否被正确的处理,不要使用如下方法:

WelcomeMailer.welcome(@user).deliver

而是要这样:

WelcomeMailer.welcome(@user.id).deliver

然后在你的 mailer 中:

class WelcomeMailer < ActionMailer::Base
  def welcome(id) @user = User.find(id)
    ...
  end
end
Switching it up

The default queueing system isRails.queue, but you can override this to use any queueing system you want by overridingActionMailer::Base#queue.

class WelcomeMailer < ActionMailer::Base
  def queue
    MyQueue.new
  end
end

Your custom queue should expect the jobs to respond to#run, same asRails.queue.

切换

默认的队列系统是 Rails.queue,但你可以自己定制一个队列系统,只需要重写 ActionMailer::Base#queue 即可:

class WelcomeMailer < ActionMailer::Base
  def queue
    MyQueue.new
  end
end

你定制的队列需要作业提供 #run 方法。

本文中的很多代码都来自于 Nick Plante‘sresque_mailer gem.


via:oschina

发表评论

电子邮件地址不会被公开。 必填项已用*标注