如何将关注模块仅包含在rails控制器中的动作
问题描述:
以下是我关心的控制器Concerns::V1::PlanFinding
。根据base
控制器和行动,它调用下面set_plan
如何将关注模块仅包含在rails控制器中的动作
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
是一个控制器,我打电话的关心:
class Dist::PlansController
include ::Concerns::V1::PlanFinding
这运行正常。但关注代码与base
控制器过多粘在一起。
我的问题是:由于我们不能在控制器中使用如下所示的only
选项。如何实现自己的only
选项包括,或找到从关注解耦base
控制器的新方法:
include Concerns::V1::PlanFinding, only: [:show]
答
据我所知,这是不可能的开箱。我用下面的办法:
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