【问题标题】:Rails 4.1 Force ActionMailer to return other valueRails 4.1强制ActionMailer返回其他值
【发布时间】:2015-08-06 16:31:41
【问题描述】:

我如何可以强制在 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") 时,返回值是#&lt;ActionMailer::Base::NullMail:0x007fe5c433ab10&gt;

谢谢!!

【问题讨论】:

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


    【解决方案1】:

    为该任务创建单独的类(不是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
    

    【讨论】:

    • require 'render_anywhere' 在第一行:)
    • 如何包含 url helper 和翻译,例如:&lt;% link_to t('test.index.link'), sign_up_url(@code) %&gt; ??
    • 我认为最好的方法是在环境中添加Rails.application.routes.default_url_options[:host] = 'localhost:3000' (config/environments/*) :)
    • 好吧,如果它有效,那么它就有效。你的sign_up_url 现在可以用了吗?
    • 好的,谢谢!!除了使用翻译我还包括ActionView::Helpers::TranslationHelper
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多