Thoughts about tech, programming, and more.

Use Base Controller

In a Rails app, when dealing with controllers that live within the same directory, we can create a base controller that those controllers can inherit from. This approach allows us to keep our code DRY and clean.

controllers/
    application_controller.rb
    admin/
        base_controller.rb
        posts_controller.rb
        comments_controller.rb

As you can see in the example folder controllers structure above, we have a base_controller.rb inside the admin/ directory.

class Admin::BaseController < Application
    before_filter :is_admin?
    def is_admin?
        # Check if user is admin
    end
end

We can then set up admin/posts_controller.rb and admin/comments_controller.rb to inherit from admin/basecontroller.rb and there’s no need to repeat before_filter :is_admin? throughout the admin controllers.

Subscribe to Daniel Lemky

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe