Created
October 13, 2008 21:27
-
-
Save Sutto/16609 to your computer and use it in GitHub Desktop.
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
# And then, our mixin. Note that it makes a few assumptions | |
module ControllerMixin | |
def self.included(parent) | |
parent.class_eval do | |
include InstanceMethods | |
extend ClassMethods | |
end | |
end | |
class InvalidUserPermissions < StandardError; end | |
module InstanceMethods | |
end | |
module ClassMethods | |
# Used for defining permissions based on the Model#can_<action>?(user) | |
# style of access control. Note that the follow is an example of | |
# usage: | |
# permissions :view, :team, :only => :index | |
def permissions(name, object_name, *args) | |
filter_name = :"check_#{name.to_s.underscore}_permissions" | |
define_method(filter_name) do | |
current_object = instance_variable_get("@#{object_name.to_s.underscore}") | |
if logged_in? and current_user.can(name.to_sym, current_object) | |
return true | |
else | |
raise InvalidUserPermissions # Optional. | |
return false | |
end | |
end | |
before_filter(filter_name, *args) | |
private filter_name | |
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
# Models can then have can_edit? etc on them which take a user | |
class SomeModel | |
belongs_to :user | |
def can_edit?(user) | |
return user == self.user | |
end | |
def can_view?(user) | |
user # any logged in user | |
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
# Our user class | |
class User | |
def can(action, target) | |
return target.respond_to?(:"can_#{action}"?) && target.send(:"can_#{action}?") | |
end | |
end | |
# and our Admin subclass | |
class Admin < User | |
def can(action, target); true; end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment