在 Rails 中发送邮件时,通常会这样做:
UserMailer.password_reset(user).deliver
但如果我们向内看UserMailer
我们可以看到这个:
def password_reset(user) # not self.password_reset
# ...
end
请注意,方法名称没有前缀self
。看看它,似乎您需要首先实例化该对象,如下所示。 Rails 是如何做到这一点的?
UserMailer.new.password_reset(user).deliver
这是一个很好的问题。在源代码中(https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb),Rails 使用 method_missing 创建 ActionMailer 的新实例。以下是来源的相关摘录:
def method_missing(method_name, *args) # :nodoc:
if respond_to?(method_name)
new(method_name, *args).message
else
super
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)