gpt4 book ai didi

ruby-on-rails - 如何在 Rails Controller 中包含仅包含操作的关注模块

转载 作者:行者123 更新时间:2023-12-03 17:16:27 24 4
gpt4 key购买 nike

以下是我关心的Concerns::V1::PlanFinding对于 Controller 。取决于 base Controller 和 Action ,它调用 set_plan

 extend ActiveSupport::Concern
attr_accessor :plan, :custom_key

included do |base|
actions = case base.to_s
when "Api::V1::PlansController"
[:show, :total_prices, :update]
when "Dist::PlansController"
[:show, :total_prices, :flight_info]
end

if actions.present?
before_action :set_plan, only: actions
else
before_action :set_plan
end
end

def set_plan
@plan = Model.find('xxx')
@custom_key = params[:custom_key] || SecureRandom.hex(10)
end

以下是我提出问题的一个 Controller :

class Dist::PlansController
include ::Concerns::V1::PlanFinding

这运行良好。但是关注代码与 base 粘得太紧了 Controller 。

我的问题是:由于我们不能使用 only Controller 中的选项如下所示。如何实现我自己的 only包含选项,或找到一种新方法来解耦 base来自关注的 Controller :
include Concerns::V1::PlanFinding, only: [:show]

最佳答案

AFAIK 这是不可能的。我使用以下方法:

PLAN_FINDING_USE = [:show]
include Concerns::V1::PlanFinding


included do |base|
actions = base.const_defined?('PLAN_FINDING_USE') &&
base.const_get('PLAN_FINDING_USE')

if actions.is_a?(Array)
before_action :set_plan, only: actions
else
before_action :set_plan
end
end

关于ruby-on-rails - 如何在 Rails Controller 中包含仅包含操作的关注模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44800673/

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