Stop returning false from your before filters 3

Posted by pratik
on Friday, July 31

In the past version of Rails you had to explicitly return false from before filters to halt the filter chain and make sure the action doesn’t get run. The code looked somewhat like :

1
2
3
4
5
6
7
8
9
10
11
12
class AdminController < ApplicationController
  before_filter :check_admin

  private

  def check_admin
    unless current_user.admin?
      redirect_to home_path
      return false
    end
  end
end

But since Rails 2.0, If you call render, head or redirect_to from a before_filter, the filter chain will be halted. So the above controller will now look like :

1
2
3
4
5
6
7
8
9
class AdminController < ApplicationController
  before_filter :check_admin

  private

  def check_admin
    redirect_to home_path unless current_user.admin?
  end
end

You should go ahead and update all your before filters to reflect this change. return false is nothing but code smell.

Comments

Leave a response

  1. Johan AnderssonJuly 31, 2009 @ 10:04 PM

    Thanks for the tip! I love great little tips like this!

  2. Evgeniy DolzhenkoAugust 04, 2009 @ 08:05 AM

    Seems a bit strange to me calling the piece of code which became obsolete just as the result of API change “nothing but code smell” :)

  3. PratikAugust 05, 2009 @ 12:36 AM

    Because it’s been 2 years and that’s a long time!! Also, I’ve seen cases where this issue caused security problems. Hence, calling it “code smell” is justified :)

Comment