2017-06-28 74 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 
相關問題