Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to include concerns module with only actions in rails controllers

Below is my concern Concerns::V1::PlanFinding for controllers. Depending on base controllers and actions, it calls 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

below is one controller where I call the concern from:

class Dist::PlansController
   include ::Concerns::V1::PlanFinding

This runs fine. but the concern code is too much glued with the base controller.

My question is: Due to we cannot use only option like below in controllers. How to implement my own only option for include, or to find a new way to decouple the base controllers from the concern:

include Concerns::V1::PlanFinding, only: [:show]
like image 765
blankdeng Avatar asked Nov 08 '22 20:11

blankdeng


1 Answers

AFAIK this is impossible out of the box. I use the following approach:

PLAN_FINDING_USE = [:show]
include Concerns::V1::PlanFinding

and

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
like image 145
Aleksei Matiushkin Avatar answered Nov 15 '22 05:11

Aleksei Matiushkin