Rails 4.1 强制 ActionMailer 为 return 其他值

Rails 4.1 Force ActionMailer to return other value

如何在 ActionMailer 方法中强制 return 另一个值。示例:

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") 时,值 return 是 #<ActionMailer::Base::NullMail:0x007fe5c433ab10>

谢谢!!

为该任务创建单独的 class(不是 ActionMailer::Base 的后代)。 ActionMailer 将重写其邮件程序操作中的 return 值。

您可以使用render_anywhere gem作为解决方案:

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