2017-06-28 41 views
1

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

回答

1

据我所知,这是不可能的开箱。我用下面的办法:

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 
相关问题