将变量从 Devise 控制器传递到自定义邮件程序?
Pass variable from Devise controller to custom mailer?
我在 Rails 应用程序中使用 Devise 进行身份验证。
在我的 registrations_controller
中,我有一个这样的变量:
class RegistrationsController < Devise::RegistrationsController
def create
foo = "bar"
super
end
end
然后在我的自定义邮件程序中尝试访问 foo
变量。 opts
参数似乎是要看的参数:
class CustomMailer < Devise::Mailer
helper :application
include Devise::Controllers::UrlHelpers
def confirmation_instructions(record, token, opts={})
Rails.logger.error opts[:foo].inspect
super
end
end
但是我如何传递 foo
变量,而不重写很多方法?
首先,阅读 Devise custom mailer 以熟悉该过程。
简而言之,您将如何去做:
在 config/initializers/devise.rb:
config.mailer = "DeviseMailer"
现在您可以像使用项目中的任何其他邮件程序一样使用 DeviseMailer:
class DeviseMailer < Devise::Mailer
helper :application # gives access to all helpers defined within `application_helper`.
include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
default template_path: 'devise/mailer' # to make sure that your mailer uses the devise views
...
def confirmation_instructions(record, token, opts={})
headers["Custom-header"] = "Bar"
opts[:from] = 'my_custom_from@domain.com'
opts[:reply_to] = 'my_custom_from@domain.com'
super
end
...
end
您现在可以在项目中调用 confirmation_instructions
并传递您希望能够在模板中访问的任何变量。
即:
调用confirmation_instructions
方法:
DeviseMailer.confirmation_instructions(User.first, "faketoken", {})
confirmation_instructions.html.erb
<p> And then override the template according to you. <p>
希望这对您有所帮助:)
我在 Rails 应用程序中使用 Devise 进行身份验证。
在我的 registrations_controller
中,我有一个这样的变量:
class RegistrationsController < Devise::RegistrationsController
def create
foo = "bar"
super
end
end
然后在我的自定义邮件程序中尝试访问 foo
变量。 opts
参数似乎是要看的参数:
class CustomMailer < Devise::Mailer
helper :application
include Devise::Controllers::UrlHelpers
def confirmation_instructions(record, token, opts={})
Rails.logger.error opts[:foo].inspect
super
end
end
但是我如何传递 foo
变量,而不重写很多方法?
首先,阅读 Devise custom mailer 以熟悉该过程。
简而言之,您将如何去做:
在 config/initializers/devise.rb:
config.mailer = "DeviseMailer"
现在您可以像使用项目中的任何其他邮件程序一样使用 DeviseMailer:
class DeviseMailer < Devise::Mailer
helper :application # gives access to all helpers defined within `application_helper`.
include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
default template_path: 'devise/mailer' # to make sure that your mailer uses the devise views
...
def confirmation_instructions(record, token, opts={})
headers["Custom-header"] = "Bar"
opts[:from] = 'my_custom_from@domain.com'
opts[:reply_to] = 'my_custom_from@domain.com'
super
end
...
end
您现在可以在项目中调用 confirmation_instructions
并传递您希望能够在模板中访问的任何变量。
即:
调用confirmation_instructions
方法:
DeviseMailer.confirmation_instructions(User.first, "faketoken", {})
confirmation_instructions.html.erb
<p> And then override the template according to you. <p>
希望这对您有所帮助:)