gpt4 book ai didi

ruby - Rails before_action for ActionMailer 将使用邮件程序参数

转载 作者:数据小太阳 更新时间:2023-10-29 06:53:48 24 4
gpt4 key购买 nike

假设我有一个发送不同电子邮件的邮件程序,但预计会使用相同的参数调用。我想为所有邮件操作处理这些参数。因此,调用一个 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, @from, @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

然后在我的 Controller /服务中我在某处做

MyMailer.actionx(*mailer_params).deliver_now

如何访问 before_action block 中的 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


更新

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

关于ruby - Rails before_action for ActionMailer 将使用邮件程序参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28634619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com