Skip to content

Instantly share code, notes, and snippets.

@isaacsanders
Created October 23, 2011 05:14
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 isaacsanders/1306906 to your computer and use it in GitHub Desktop.
Save isaacsanders/1306906 to your computer and use it in GitHub Desktop.
ReUser Examples
# ReUser can be used in many ways
require 'reuser'
class User
# You always need to include ReUser to get the methods on the class
include ReUser
# You start your role definitions by passing a block to the `roles` method.
# Otherwise, it returns a hash of your roles
roles do
# A role is defined with the `role` method. `role` returns a ReUser::Role.
# ReUser::Role has the `can` method defined on it.
# `can` takes a list of actions.
role(:root).can :read, :write, :execute
# Optionally, you can pass a block to `role`
role(:user) do |usr|
# You can define a role in many steps.
usr.can :execute
# `could` is my favorite part of ReUser.
# Instead of blindly allowing a User to do anything with anything,
# `could` allows the user to define a test block to send objects to.
# You can mix and match `could` actions and `can` actions. ReUser knows
# that if the User doesn't take have a test declared for the action, it
# needs to pass it, regardless of the object sent.
usr.could :read, :write do |file|
file.owner?(usr)
end
end
# This is the third syntax you can use for declaring your roles.
# The Array is just another list of actions that the guest can do.
role(:guest, [:read, :browse, :explore])
end
end
# In Rails:
class User < ActiveRecord::Base
include ReUser
# Role definition
roles do
role(:admin).can :read, :write, :execute
role(:user).could :read, :write do |file|
file.owner? self
end
end
# ReUser requires the #role method to return the
# name of the User's role
end
# Once you have declared your roles, you can begin testing them in your controllers/views
class UsersController < ApplicationController
before_filter :get_user
def index
# This is a simple use of `can?`
if @user.can? :execute
redirect_to url_for(:action => __caller__, :controller => 'admins')
else
respond_to {|f| f.html}
end
end
end
class FilesController < ApplicationController
before_filter :get_user
def read
@file = File.find(params[:id])
# Here we are using `could?`, which will use the second argument
# as the block variable in our `could` test block in the User model.
# `could?` will return true if the @file passes the test.
if @user.could? :read, @file
respond_to {|f| f.html}
else
render :status => 401
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment