Rails 4.1强制ActionMailer返回其他值

时间:2015-08-06 16:31:41

标签: ruby-on-rails ruby ruby-on-rails-4 actionmailer

如何强制在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("xxxx@gmail.com", "asdf123")时,值返回为#<ActionMailer::Base::NullMail:0x007fe5c433ab10>

谢谢!

1 个答案:

答案 0 :(得分:2)

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

您可以使用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