Created
October 19, 2013 19:21
-
-
Save yesmeck/7060244 to your computer and use it in GitHub Desktop.
Rails 4 user role constraint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ?