Skip to content

Instantly share code, notes, and snippets.

@yesmeck
Created October 19, 2013 19:21
Show Gist options
  • Save yesmeck/7060244 to your computer and use it in GitHub Desktop.
Save yesmeck/7060244 to your computer and use it in GitHub Desktop.
Rails 4 user role constraint
# app/constraints/role_constraint.rb
class RoleConstraint
def initialize(*roles)
@roles = roles.map { |r| r.to_s }
end
def matches?(request)
@roles.include? request.env['warden'].user(:user).try(:role)
end
end
# config/route.rb
root :to => 'admin#index', :constraints => RoleConstraint.new(:admin) #matches this route when the current user is an admin
root :to => 'sites#index', :constraints => RoleConstraint.new(:user) #matches this route when the current user is an user
root :to => 'home#index' #matches this route when the above two matches don't pass
@zx1986
Copy link

zx1986 commented Dec 5, 2014

hello, I came to here from Google, and follow an old post:
http://minhajuddin.com/2011/10/24/how-to-change-the-rails-root-url-based-on-the-user-or-role

But I couldn't let this beautiful trick works.
Should I put role_constraint.rb in app/lib ?

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