HAL is a class-based authorization framework for Ruby. It lets you define authorization rules on classes, which will then be applied to all instances of said classes. For example:
class User < Struct.new(:name); end dave = User.new("Dave") HAL.rules_for User do def open_the_pod_bay_doors? subject.name != "Dave" end end HAL.can(dave).open_the_pod_bay_doors? #=> false
When defining rules you can access a subject
method, which will reference whatever object you pass to can
.
You also have a more powerful version of can
, called can!
, which takes a block and will raise HAL::ICantLetYouDoThat
if the block evaluates to false:
HAL.can!(dave) {|can| can.open_the_pod_bay_doors? } #=> raises!
Finally, you can include HAL
into your classes to get can
and can!
as helper methods.
class UsersController < ApplicationController include HAL before_filter :check_permissions, :only => [:edit, :update, :destroy] def check_permissions unless can(current_user).edit_user?(current_user) redirect_to users_path, :alert => "I can't let you do that, Dave" end end end
As a RubyGem
gem install hal
For rails 2.3, add to your config/environment.rb:
config.gem "hal", :lib => "hal/rails"
For rails 3, add to your Gemfile:
gem "hal", :require => "hal/rails"