Rails 4.1强制ActionMailer返回其他值 [英] Rails 4.1 Force ActionMailer to return other value
问题描述
我如何可以强制在ActionMailer方法中返回另一个值。示例:
how to i can force to return another value in ActionMailer method. Example:
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( xxxx@gmail.com, asdf123)
时,返回值是#< ActionMailer :: Base :: NullMail:0x007fe5c433ab10>
In this case i use ActionMailer to render template(render_to_string) and pass variables to the view, but i need get result value from MandrillApi module. When i call the method TestMailer.index("xxxx@gmail.com", "asdf123")
the value return is #<ActionMailer::Base::NullMail:0x007fe5c433ab10>
谢谢!
推荐答案
为该任务创建单独的类(不是 ActionMailer :: Base
的后代)。 ActionMailer将从其邮件操作中重写返回值。
Create separate class (not a descendant of ActionMailer::Base
) for that task. ActionMailer will rewrite return values from its mailer actions.
您可以使用 render_anywhere gem作为解决方案:
You can use render_anywhere gem as a solution:
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("user@example.org", "asdf123") # => result of MandrilApi.send
这篇关于Rails 4.1强制ActionMailer返回其他值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!