未定义邮件时,如何在邮件程序上调用类方法? [英] How can you call class methods on mailers when they're not defined as such?
问题描述
在Rails中发送邮件时,通常会执行以下操作:
When sending mail in Rails, usually one would do something like this:
UserMailer.password_reset(user).deliver
但是,如果我们查看UserMailer
的内部,我们会看到:
But if we look inside UserMailer
we can see this:
def password_reset(user) # not self.password_reset
# ...
end
请注意,方法名称不带self
前缀.看起来,您似乎需要首先实例化该对象,如下所示. Rails如何做到这一点?
Notice that the method name is not prefixed with self
. Looking at it, it seems like you need to instantiate the object first as below. How does Rails do this?
UserMailer.new.password_reset(user).deliver
推荐答案
这是一个很好的问题.在源代码中( https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb ),Rails使用method_missing创建ActionMailer的新实例.这是源代码中的相关摘录:
That's a great question. In the source (https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb), Rails uses method_missing to create a new instance of the ActionMailer. Here's the relevant excerpt from the source:
def method_missing(method_name, *args) # :nodoc:
if respond_to?(method_name)
new(method_name, *args).message
else
super
end
end
这篇关于未定义邮件时,如何在邮件程序上调用类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!