如何为Devise邮件内容添加环境条件判断?
解决Devise邮件添加环境专属信息的方案
方法1:自定义Devise邮件模板(最直观)
Devise默认邮件模板封装在gem中,你可以先将模板生成到项目本地,直接在模板里用ERB语法插入环境变量:
- 生成邮件模板到项目:
rails generate devise:views mailer
执行后,app/views/devise/mailer/目录会出现所有Devise邮件模板(如reset_password_instructions.html.erb、reset_password_instructions.text.erb)。
- 修改模板内容:
打开对应模板,在标题或正文加入环境标识逻辑,比如仅非生产环境显示提示:
<% unless Rails.env.production? %> <div style="background: #fff3cd; padding: 10px; text-align: center; font-weight: bold;"> 【<%= Rails.env.upcase %>环境】此邮件为测试用途,请勿用于正式操作 </div> <% end %> <h2><%= Rails.env.production? ? '' : "[#{Rails.env.upcase}] " %>重置密码指引</h2>
方法2:重写Devise邮件的subject方法(集中管理)
若不想修改模板,可通过重写邮件类方法动态设置主题:
- 在
app/mailers/创建custom_devise_mailer.rb:
class CustomDeviseMailer < Devise::Mailer def reset_password_instructions(record, token, opts = {}) env_prefix = Rails.env.production? ? '' : "[#{Rails.env.upcase}] " opts[:subject] = "#{env_prefix}#{I18n.t('devise.mailer.reset_password_instructions.subject')}" super(record, token, opts) end # 同理可重写确认邮件等其他Devise邮件方法 def confirmation_instructions(record, token, opts = {}) env_prefix = Rails.env.production? ? '' : "[#{Rails.env.upcase}] " opts[:subject] = "#{env_prefix}#{I18n.t('devise.mailer.confirmation_instructions.subject')}" super(record, token, opts) end end
- 在
config/initializers/devise.rb配置使用自定义邮件类:
Devise.setup do |config| config.mailer = 'CustomDeviseMailer' end
方法3:让YAML文件支持ERB解析(需全局配置)
Rails默认不解析locale YAML中的ERB,可修改config/application.rb开启预处理:
module YourAppName class Application < Rails::Application # 替换原有i18n加载路径配置,让YAML文件经过ERB解析 config.i18n.load_path = Dir[Rails.root.join('config', 'locales', '**', '*.yml')].map do |path| ERB.new(File.read(path)).result end end end
随后将devise.en.yml改名为devise.en.yml.erb,即可在其中使用ERB语法:
en: devise: mailer: reset_password_instructions: subject: "<%= Rails.env.production? ? '' : "[#{Rails.env.upcase}] " %>Reset password instructions"
注意:此方法会影响所有locale文件的加载逻辑,需测试验证兼容性。
内容的提问来源于stack exchange,提问作者TddOrBust
相关产品推荐
相关产品推荐

