在actionmailer中,如何在运行时覆盖default_url_options?

时间:2012-02-07 16:38:34

标签: ruby-on-rails actionmailer

我需要能够生成链接到所有运行我的应用程序但具有不同域名的网站(我正在运行白标签服务)。

代表这些域发送的电子邮件根据邮件设置不同的主机。

通常我会设置host application.rb

config.action_mailer.default_url_options[:host] = 'myhost.com'

但是,因为我的主机根据我试图在运行时尝试这样做的链接而变化。

user_mailer.rb

Rails.configuration.action_mailer.default_url_options[:host] = new_host
mail(...)

问题在于,每次运行此操作时,它都会继续使用application.rb中定义的任何内容。我似乎无法让应用程序尊重新定义的default_url_optiions[:host]值。我做错了什么?

2 个答案:

答案 0 :(得分:1)

如果没有很多视图你可以简单地在url_for帮助器上定义主机,如果有太多的视图,我建议你编写自己的帮助器,用@ {1包装url_for帮助器}}

答案 1 :(得分:0)

使用class_attribute在ActionMailer上设置default_url_options方法,该类是在Class的ActiveSupport核心扩展中定义的。根据文档,它还提供了一个实例级访问器,可以在每个实例的基础上覆盖,而不会影响类级方法。因此,您应该可以直接为每封电子邮件覆盖主机设置

class UserMailer < ActionMailer::Base
  def welcome(user)
    @user = user

    # don't need this if you override #mail method.
    self.default_url_options = default_url_options.merge(host: @user.host)

    mail(to: user.email, subject: "Welcome")
  end

  # might be better to override mail method if you need it for all emails in
  # a particular mailer
  private

  def mail(headers, &block)
    self.default_url_options = default_url_options.merge(host: @user.host)

    super
  end
end

这应该允许您在运行时修改设置;请忽略@ user.host调用并将其替换为您确定主机。