against convention

Jared Carroll

In Rails we have these nice things we can use in our controllers called filters. A filter is simply a method that will get executed before, after or around the execution of a specific action in a controller. After looking at a bunch of different Rails apps, I never liked any of the names given to these filter methods.

For example:

class UsersController < ApplicationController

  before_filter :ensure_logged_in

  def show
    @user = User.find params[:id]
  end

 private

  def ensure_logged_in
    unless session[:user_id]
      flash[:notice] = 'You must log in'
      redirect_to new_session_path
    end
  end

end

I’ve seen this technique of prefixing the word ‘ensure’ to filter names. I think this sucks and results in long ugly method names.

I’ve also seen this:

class UsersController < ApplicationController

  before_filter :require_logged_in

  def show
    @user = User.find params[:id]
  end

 private

  def require_logged_in
    unless session[:user_id]
      flash[:notice] = 'You must log in'
      redirect_to new_session_path
    end
  end

end

Prefixing all filter names with ‘require’. Same thing as ‘ensure’; long ugly method names.

I’ve adopted the following convention:

class UsersController < ApplicationController

  before_filter :logged_in?

  def show
    @user = User.find params[:id]
  end

 private

  def logged_in?
    unless session[:user_id]
      flash[:notice] = 'You must log in'
      redirect_to new_session_path
    end
  end

end

Now this flies in the face of normal Ruby use of the ‘?’ operator, i.e. it should only be used for query methods (methods that return a boolean). But it reads so much better and the method name is nice and short.

About thoughtbot

We've been helping engineering teams deliver exceptional products for over 20 years. Our designers, developers, and product managers work closely with teams to solve your toughest software challenges through collaborative design and development. Learn more about us.