【问题标题】:how to include concerns module with only actions in rails controllers如何在 Rails 控制器中包含仅包含操作的关注模块
【发布时间】:2017-12-01 17:04:00
【问题描述】:

以下是我对控制器的关注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]

【问题讨论】:

    标签: ruby-on-rails ruby include activesupport-concern


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 2020-03-17
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多