Created
June 7, 2011 00:50
-
-
Save saturnflyer/1011449 to your computer and use it in GitHub Desktop.
Simple permissions
This file contains hidden or 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
# A small example of Method Forwarding | |
# | |
# The permissions are stored on the object concerned with access control. | |
# You send a message to one object, which forwards it to the access controller. | |
class User | |
attr_accessor :zombie | |
def method_missing(meth, object, *args) | |
if object.permissions | |
object.send(meth, self, *args) | |
else | |
super | |
end | |
end | |
end | |
class Site | |
attr_accessor :permissions | |
class Permissions | |
def allowed?(user) | |
!user.zombie | |
end | |
def can_do_things?(user) | |
false | |
end | |
end | |
def initialize | |
self.permissions = Permissions.new | |
end | |
def method_missing(meth, *args) | |
options = args.last.is_a?(Hash) ? args.pop : {} | |
object = args.shift | |
permissions.send(meth, object, *args) | |
rescue NoMethodError | |
super | |
end | |
end | |
site = Site.new | |
user = User.new | |
zombie = User.new | |
zombie.zombie = true | |
puts "user.can_do_things?(site) #=> #{user.can_do_things?(site)}" | |
puts "zombie.can_do_things?(site) #=> #{zombie.can_do_things?(site)}" | |
puts "user.allowed?(site) #=> #{user.allowed?(site)}" | |
puts "zombie.allowed?(site) #=> #{zombie.allowed?(site)}" | |
puts "site.allowed?(user) #=> #{site.allowed?(user)}" | |
puts "site.allowed?(zombie) #=> #{site.allowed?(zombie)}" | |
puts "user.unknown_method?(site) #=> #{user.unknown_method?(site)}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment