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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With