Skip to content

Instantly share code, notes, and snippets.

@saturnflyer
Created June 7, 2011 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saturnflyer/1011449 to your computer and use it in GitHub Desktop.
Save saturnflyer/1011449 to your computer and use it in GitHub Desktop.
Simple permissions
# 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