加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 用于ActionMailer的Rails before_action,它将使用邮件程

发布时间:2020-12-17 04:16:09 所属栏目:百科 来源:网络整理
导读:假设我有一个邮件发送不同的电子邮件,但预计将使用相同的参数调用.我想为所有邮件程序操作处理这些参数.因此,调用before_action将读取发送到邮件程序方法的参数 /mailers/my_mailer.rbclass MyMailer ApplicationMailer before_filter do |c| # c.prepare_ma
假设我有一个邮件发送不同的电子邮件,但预计将使用相同的参数调用.我想为所有邮件程序操作处理这些参数.因此,调用before_action将读取发送到邮件程序方法的参数
/mailers/my_mailer.rb
class MyMailer < ApplicationMailer
    before_filter do |c|
      # c.prepare_mail # Will fail,because I need to pass `same_param` arguments
      # # I want to send the original arguments
      # c.prepare_mail(same_param) # How do I get `same_param` here ?
    end

    def action1(same_param)
      # email view is going to use @to,@from,@context    
      method_only_specific_to_action1
    end

    def action2(same_param)
      # email view is going to use @to,@context
      method_only_specific_to_action2
    end

    private
      def prepare_mail(same_params)
        @to = same_params.recipient
        @from = same_params.initiator
        @context = same_params.context
      end
    end

然后在我的控制器/服务中我做某个地方

MyMailer.actionx(*mailer_params).deliver_now

如何访问before_action块中的same_param参数列表?

编辑:

我想重构一下

/mailers/my_mailer.rb
class MyMailer < ApplicationMailer

    def action1(same_param)
      @to = same_params.recipient
      @from = same_params.initiator
      @context = same_params.context   
      method_only_specific_to_action1
    end

    def action2(same_param)
      @to = same_params.recipient
      @from = same_params.initiator
      @context = same_params.context   
      method_only_specific_to_action2
    end

    def actionx
      ... 
    end
  end

而这个重构

/mailers/my_mailer.rb
class MyMailer < ApplicationMailer

    def action1(same_param)
      prepare_mail(same_params)   
      method_only_specific_to_action1
    end

    def action2(same_param)
      prepare_mail(same_params)   
      method_only_specific_to_action2
    end

    def actionx
      ... 
    end

    private
      def prepare_mail(same_params)
        @to = same_params.recipient
        @from = same_params.initiator
        @context = same_params.context
      end
    end

感觉非最佳(prepare_mail(same_params)在每个动作中重复)

因此,上面提出了什么

解决方法

ActionMailer使用AbstractController :: Callbacks模块.我尝试过它似乎对我有用.

代码

class MyMailer < ApplicationMailer
  def process_action(*args)
    # process the args here
    puts args
    super
  end

  def some_mail(*args)
  end
end

MyMailer.some_mail(1,2) #=> prints ['some_mail',1,2]

The documentation

UPDATE

如果您使用的是Rails 5.1,可以查看ActionMailer::Parameterized

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读