【问题标题】:Override to field in ActionMailer based on environment根据环境覆盖到 ActionMailer 中的字段
【发布时间】:2015-02-06 23:45:01
【问题描述】:

我正在使用 Rails 4.2 想要覆盖特定环境下所有 ActionMailer 邮件程序的 to 字段。在这种情况下,我想覆盖 Staging 中使用的所有邮件程序的 to 字段。我的目标是让暂存环境以与生产环境完全相同的方式传递邮件,但将其全部转储到测试收件箱中。

我知道有一些服务可以帮助解决这个问题,但我的目标是使用我的生产 API 进行分阶段交付作为全面测试。

我希望我可以在邮件启动之前使用 mixin 或其他东西来重置 to 字段。

【问题讨论】:

    标签: ruby-on-rails ruby actionmailer


    【解决方案1】:

    不确定您使用的是什么版本的 Rails,但您可以考虑使用新的邮件拦截器来完成此操作。

    主要优点是它不会直接弄乱您的 ActionMailer 类。

    http://guides.rubyonrails.org/action_mailer_basics.html#intercepting-emails

    复制他们的例子:

    class SandboxEmailInterceptor
      def self.delivering_email(message)
        message.to = ['sandbox@example.com']
      end
    end
    

    config/initializers/sandbox_email_interceptor.rb:

    ActionMailer::Base.register_interceptor(SandboxEmailInterceptor) if Rails.env.staging?
    

    【讨论】:

    • 我使用的是 Rails 4.2,这正是我要找的!
    【解决方案2】:

    最简单的方法是检查正在运行的环境并相应地设置to 字段。例如,一个简单的密码重置邮件可能看起来像:

    class UserMailer < ActionMailer::Base
      default from: "support@example.com"
    
      def reset_password(user_id)
        @user = User.find(user_id)
        @url  = reset_password_users_url(token: @user.password_reset_token)
    
        mail(to: @user.email, subject: '[Example] Please reset your password')
      end
    end
    

    现在检查暂存环境并将所有这些电子邮件路由到admin@example.com

    class UserMailer < ActionMailer::Base
      default from: "support@example.com"
    
      def reset_password(user_id)
        @user = User.find(user_id)
        @url  = reset_password_users_url(token: @user.password_reset_token)
    
        to = Rails.env.staging? ? 'admin@example.com' : @user.email
        mail(to: to, subject: '[Example] Please reset your password')
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      相关资源
      最近更新 更多