Rails ApplicationMailer 奇怪的调用方法

zengfengbo · December 24, 2016 · Last by mengqing replied at January 03, 2017 · 1758 hits

正常的方法调用

class A
  def self.f1
    puts "the method of class"
  end
  def f2
    puts "the method of instance"
  end
end

A.f1
A.new.f2

UserMailer 的方法调用

class UserMailer < ApplicationMailer
  def account_activation(user)
    @user = user
    mail(to: @user.email, subject: '激活帐号.')
  end
end

UserMailer.account_activation(@user).deliver_now

不应该是这样调用么?

UserMailer.new.account_activation(@user).deliver_now

我记得论坛有人问过,搜索下。大概记得是 method missing 触发后查找实例方法,具体可以去追踪下源码。

谢谢,@blacktulip。还是存疑,为什么要绕一下,设置成这样。

这是因为 actionmailer 的设计理念。因为 ActionMailer 的父类是一个 Controller,而 Controller 理论上只应该应对一个 action。ActionMailer 所以要防止你写这样的代码

user_mailer = UserMailer.new
user_mailer.foo
user_mailer.bar
You need to Sign in before reply, if you don't have an account, please Sign up first.