Created
May 13, 2009 16:38
-
-
Save ianterrell/111115 to your computer and use it in GitHub Desktop.
Implementation for Authorization plugin
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
# This lets you define user roles as methods, | |
# i.e. checking the role of "admin" on a user | |
# will delegate to user.admin? | |
# | |
# This is helpful because in ActiveRecord, boolean | |
# attributes automatically have their query method | |
# defined; a boolean field "admin" will define | |
# the "admin?" method for you. | |
# | |
# If your logic is more complex, you can write your | |
# own methods. | |
def has_role?(role) | |
self.respond_to?(:"#{role}?") && self.send(:"#{role}?") | |
end | |
# This delegates role checks to methods as well, but | |
# in two cases: | |
# | |
# First, it will check the singular option. An example | |
# would be the role of "owner of :group"; it will check to see | |
# if the group has an "owner" method, and if so will check | |
# if group.owner == user. | |
# | |
# Second, if a singular method is not found, it will check the | |
# plural method. A better example would be the role of | |
# "member of :group"; it will check to see if the group | |
# has a "members" method, and if so will check if the | |
# user is in that collection. | |
# | |
# This is a helpful implementation because it allows | |
# ActiveRecord associations to serve as your roles. | |
# | |
# Again, if your needs are more complex, you can | |
# overwrite the methods. | |
def accepts_role?(role, user) | |
if self.respond_to? role | |
self.send(role) == user | |
elsif self.respond_to? role.pluralize | |
self.send(role.pluralize).include? user | |
else | |
false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment