Search code examples
ruby-on-rails-3before-filter

Rails use not condition with before_filter


I'm using before_filter in my application. I have a method logged_in? which returns true if the user is logged in.

def logged_in?
  !!current_user
end

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

Now in my users controller I want an action to execute only if a user is not logged in. For this I want to use the not condition with logged_in? method in before_filter as:

before_filter :!(logged_in?)

But this gives me an error. I'm resisting creating a new method for not logged in.

Please help me figure out the correct syntax to accomplish this.


Solution

  • You could pass a block to before_filter:

    before_filter { |c| !c.logged_in? }
    

    But this wouldn't really do anything, since the return value from the before filter isn't going anywhere. If you want to execute an action if a user is not logged in, then you should be putting that action into the before_filter.

    For example, if the action was to redirect to the login page, path, you could do this:

    before_filter { |c| redirect_to login_path unless c.logged_in? }
    

    That's actually long enough to justify a method of its own:

    before_filter :login_required
    
    def login_required
      redirect_to login_path unless logged_in?
    end