Skip to content

Instantly share code, notes, and snippets.

@m1foley
Last active December 16, 2015 07:28
Show Gist options
  • Save m1foley/5398526 to your computer and use it in GitHub Desktop.
Save m1foley/5398526 to your computer and use it in GitHub Desktop.
class FooController < ApplicationController
before_filter :user_required!
before_filter :admin_required!, :only => [:secret]
def not_secret
end
def secret
end
end
class ApplicationController < ActionController::Base
def user_required!
raise Exception.new('must be user') if !current_user
end
def admin_required!
raise Exception.new('must be admin') if !current_user.try(:admin?)
end
def current_user
return @current_user if defined?(@current_user)
@current_user = User.find(session[:user_id])
end
end
@bf4
Copy link

bf4 commented Apr 16, 2013

cool

It would probably be better to raise a StandardError, or even better custom errors NoUserError, NotAdminError etc

Also, since an non-declared instance variable is nil, you don't need the defined?

def current_user
@current_user ||= User.find_by_user_id(session[:user_id]) || AnonymousUser.new(session)
end

def admin_user?
current_user.admin?
end

def anonymous_user?
current_user.anonymous?
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment