Last Updated: February 25, 2016
·
501
· yonbergman

Extracting Controller Behaviours

I find myself wanting to extract controller behaviour a lot these days. Sometimes for code clarity and trying to separate object so that each has a single responsibility, and sometimes because I want to share the behaviour across controllers.

I gave a talk last month in #railsisrael where I talked about a convention we recently came up with of using ActiveSupport:Concern to extract controller behaviours and still use such things as before_filter or helper_method.

I decided to take it to the next level and write something that wraps ActiveSupport::Concern and lets you write even less code! Check the full readme and code in my repo https://github.com/yonbergman/controller_support


The idea is to extract whatever behaviour you want into a mixin'able module which you can then mixin into Controllers & also into other objects such as mailers or test stubs.

Here's an example of defining a UserSupport

module UserSupport
    extend ControllerSupport::Base

    helper_method :current_user, :user_signed_in
    before_filter :must_be_signed_in

    def current_user
        @user ||= User.find(session[:user_id])
    end

    def user_signed_in?
        current_user.present?
    end

    def must_be_signed_in
        redirect_to sign_up_path unless user_signed_in?
    end

end

and the usage is really simple

class ApplicationController
    include UserSupport
end