filter methods in before_action after of another before_action

682 Views Asked by At

how can I filter a second before_action?, I have two controllers, and when I call the method A, a before_action executes a methodB, but before executing this second method I would like to execute a general methodC, but in this method I need to pass a parameter to know where is coming from, but if I use a second before_action this doesn't work, because "only" in before_action filters using the first method method (which is methodA), what can I do?

class FirstController < SecondController
    before_action :methodB

    def methodA
       #some code
    end
end
    
class SecondController < ApplicationController
   before_action only: [:methodB] do
       methodC('methodB')
   end

   def methodB
     #some code new
   end
end

class ApplicationController < ActionController::Base
    def methodC(method)
       #general method
    end
end

This is the structure that I have: enter image description here

1

There are 1 best solutions below

4
Nick Hyland On

I'm out of practice with rails but would the following be acceptable?

class FirstController < SecondController
    before_action :methodB

    def methodA
       #some code
    end

    private

    def should_call_C
      action_name == :methodA
    end
end
    
class SecondController < ApplicationController
   before_action do |controller|
       methodC if controller.should_call_C
   end

   def methodB
     #some code new
   end

   private

   def should_call_C
     action_name == :methodB
   end
end

class ApplicationController < ActionController::Base
    def methodC
       #general method
       # can use action name to get method rather than passing it?
    end
end