Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

ruby on rails - filter methods in before_action after of another before_action

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

question from:https://stackoverflow.com/questions/65881109/filter-methods-in-before-action-after-of-another-before-action

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...