Search code examples
ruby-on-railsactioncontrollers

Access the except part of before_action in the controller itself


So I have a controller, say

class RandomActionController < ApplicationController

and I have a method check_authorization in ApplicationController that I use in RandomActionController as

before_action :check_authorization, except: [:create, :get_actions, ..]

Now in another action inside RandomActionController, I might be building an array of actions excluding ones in the except section of check_authorization, or whatever. My problem is, how do I get those actions as a hash/array or any other form?


Solution

  • What you are passing to the except part is a literal array, string or symbol. Rails does not let you (afaik) introspect a controller callback to extract the arguments it was declared with.

    If you want to be able to a re-use list of actions it you need to link it to an identifier.

    For example this a pattern I often use:

    class ApplicationController
    
      private
    
      def self.member_actions
        [:show, :edit, :destroy, :update]
      end
    
      def self.collection_actions
        [:new, :index, :create]
      end
    end
    
    class FooController < ApplicationController
      before_action :set_foo, only: member_actions
    
      def self.member_actions
        super + [:fuzzle, :wuzzle]
      end 
    end
    

    But you can just as well use constants or anything else that is available in the class context.