如何在 rails 控制器中包含仅具有操作的关注模块

how to include concerns module with only actions in rails controllers

以下是我对控制器的关注Concerns::V1::PlanFinding。根据 base 个控制器和操作,它调用 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

下面是一个控制器,我在其中提出了问题:

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