Search code examples
ruby-on-railscontrollerbefore-filter

rails skip_before_filter within method (after other before_filters have been run)


In application_controller.rb I have the following:

before_filter :get_events
before_filter :get_sitemap
def login_required
    return true if session[:user]
    # If we get to this point, I want to avoid running get_events and get_sitemap
    flash[:warning] = 'Please login to continue'
    redirect_to login_users_url
    return false 
end

And in other controllers I have for example:

before_filter :login_required, :except => [:show]

So essentially I have methods running that access the database for all pages except I don't want it to happen when the user is required to log in (i.e., being redirected from a page where normally get_events and get_sitemap are required).

I realize one way of doing this is to run login_required as a before_filter on ALL controllers before any other before_filters are set and then exclude certain controller models but I'd like to know if there's a way of doing it without having to change all my controllers.


Solution

  • Well after considering Joshua's answer I still couldn't get what I wanted to go for...so what I did was do a little hybrid solution. All controllers still reference ApplicationController, but within ApplicationController I always run the before_filter :login_required FIRST before other before_filters. Redirects in rails seem to stop other before_filters from running, which is what I wanted. In the other controllers I use the skip_before_filter :login_required, :only => [:this_time] wherever necessary.