5

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]

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.