Created
May 13, 2011 16:40
-
-
Save EmmanuelOga/970853 to your computer and use it in GitHub Desktop.
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
# Example: | |
class Product < Struct.new(:user_id); end | |
class Account < Struct.new(:user_id, :members); end | |
class User < Struct.new(:id); end | |
Permissions.for(Account) do | |
def can_read?(user) | |
members.include?(user) | |
end | |
end | |
Permissions.for(Product, Account) do | |
def can_manage?(user) | |
user_id == user.id | |
end | |
end | |
Permissions.for(User) do | |
def can_manage?(target) | |
target.user_id == id | |
end | |
def can_read?(target) | |
true | |
end | |
end | |
################################################################################ | |
include Permissions::Helper | |
def current_user | |
$user ||= User.new 1234 | |
end | |
prod = Product.new current_user.id | |
acc = Account.new 7890, [1,2,3] | |
puts can?(:read, acc) | |
puts can?(:manage, acc) | |
puts can?(:something, prod) | |
puts can?(:manage, prod) | |
puts can?(:read, prod) |
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
module Permissions | |
def self.for(*where, &block) | |
where.each { |klass| klass.class_eval(&block) } | |
end | |
module Helper | |
def can?(action, target, who=current_user) | |
perm = "can_#{action}?" | |
who.respond_to?(perm) && who.send(perm, target) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment