如何强制在 ActionMailer 方法中返回另一个值。例子:
class TestMailer < ActionMailer::Base
extend MandrillApi
def index(email, code)
@code = code
result = MandrillApi.send({subject: t('test.index.subject'), to: email, template: render_to_string})
return result
end
end
在本例中,我使用 ActionMailer 来渲染模板(render_to_string)并将变量传递给视图,但我需要从 MandrillApi 模块获取结果值。当我调用该方法时TestMailer.index("[email protected] /cdn-cgi/l/email-protection", "asdf123")
返回值是#<ActionMailer::Base::NullMail:0x007fe5c433ab10>
Thanks!!
创建单独的类(不是其后代ActionMailer::Base
)用于该任务。 ActionMailer 将重写其邮件操作的返回值。
您可以使用随处渲染 https://github.com/yappbox/render_anywhere宝石作为解决方案:
require 'render_anywhere'
class MandrilMailer
extend MandrillApi
include RenderAnywhere
# We need that for 't' i18n helper to work
include ActionView::Helpers::TranslationHelper
class RenderingController < RenderAnywhere::RenderingController
# we can use that for url_helpers to work properly
def default_url_options
host = {'production' => 'production.example.org', 'development' => 'development.example.org'}[Rails.env]
{host: host}
end
# alternatively, you can add this line inside you config/environments/*.rb files, setting your own host:
# Rails.application.routes.default_url_options[:host] = 'example.org'
end
def index(email, code)
# 'render' is a RenderAnywhere call
MandrilApi.send({subject: t('test.index.subject'), to: email, template: render(template: 'test_mailer/index', locals: {code: code}, layout: false)})
end
end
MandrilMailer.new.index("[email protected] /cdn-cgi/l/email-protection", "asdf123") # => result of MandrilApi.send
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)