ruby-on-railsruby-on-rails-4ruby-on-rails-4.2actionpack

Filter for namespaced controllers


I have a set of controllers in the folder /controllers/admin that all look like this and having the same filter:

module Admin
  class UsersController < ApplicationController
    before_action :some_method

    #actions
  end
end

How could each namespaced controller inherit the before_action :some_method from a central place?


Solution

  • It seems you need an individual Base controller within Admin module namespace:

    class Admin::BaseController < ApplicationController
      before_action :some_method
    
      #actions
    end
    
    class Admin::UsersController < Admin::BaseController
      #some_method filter is invoked here
    end
    
    class Admin::PostsController < Admin::BaseController
      #some_method filter is invoke here
    end