Rails ActionMailer中两个类调用default方法的区别是什么?
问题解答
1. ApplicationMailer中default方法的作用
ApplicationMailer是所有自定义邮件器的父类(比如示例里的UserMailer),它里面的default方法是用来定义所有子邮件器的基础默认配置。任何继承自它的邮件类,都会自动继承这些默认设置,不用每个子类重复编写相同的配置项。
2. 两次在不同类中调用default的最终效果
子类(UserMailer)里的default配置会覆盖父类(ApplicationMailer)中同名的配置项,父类中存在但子类未定义的配置项,则会被子类继承:
- 示例中两者都设置了
from字段,UserMailer发送邮件时,默认发件人会使用子类自己设置的notifications@example.com,而非父类的from@example.com; - 如果ApplicationMailer还设置了其他配置(比如
reply_to: "support@example.com"),而UserMailer没有重新定义这个项,那么UserMailer的邮件会自动沿用父类的reply_to默认值。
举个更完整的示例:
# app/mailers/application_mailer.rb class ApplicationMailer < ActionMailer::Base default from: "from@example.com", reply_to: "support@example.com" end # app/mailers/user_mailer.rb class UserMailer < ApplicationMailer default from: "notifications@example.com" end
此时UserMailer的默认配置为:from: "notifications@example.com"(子类覆盖)、reply_to: "support@example.com"(继承父类)。
内容的提问来源于stack exchange,提问作者mewi
相关产品推荐
相关产品推荐

