Skip to content

Instantly share code, notes, and snippets.

@Sutto
Created October 13, 2008 21:27
Show Gist options
  • Save Sutto/16609 to your computer and use it in GitHub Desktop.
Save Sutto/16609 to your computer and use it in GitHub Desktop.
# 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
# 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
# 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