Every repository with this icon (
Every repository with this icon (
Home
Welcome to the acts_as_checkpoint wiki!
Quick start guides
The problem
In my Rails project, users can belong to any of a number of roles — “administrator,” “superuser,” and plain old “user,” for example. Using before_filter, restricting certain actions to users belonging to one specific role is simple.
class ApplicationController < ActionController::Base def admin_required- Check for admin role
end
end
The problem I ran into, though, was that there isn’t an elegant way to restrict actions to users belonging to any of a number of roles. Depending on how many roles you have (and valid combinations thereof), this can get pretty nasty.
class ApplicationController < ActionController::Base def admin_or_superuser_required- Check for admin OR superuser roles
end
def admin_or_superuser_or_user_required - Check for admin OR superuser OR user roles
end
def superuser_or_user_required - Check for superuser OR user roles
end
end
Something like this certainly works, but it isn’t very tenable.
The solution: acts_as_checkpoint
With acts_as_checkpoint, expressing more complex before_filter behaviors in your controllers is reduced to a few lines of code.
class CoolController < ApplicationController acts_as_checkpoint controller_allows :administrator?, :to => [ :edit, :update, :destroy ] controller_allows :superuser?, :to => [ :new, :create, :edit, :update ] controller_allows :user?, :to => [ :new, :create ] endThe concept of role-based permission checking is also extended to ActiveRecord models. In addition to specifying roles allowed to perform particular actions, you may also specify associations defined in the model, as well as “self”.
class Dog < ActiveRecord::Base belongs_to :owner, :class_name => ‘Human’, :foreign_key => ‘owner_id’ acts_as_checkpoint model_may :bite, :lick model_allows :owner, :to => :pet model_allows :self, :to => :lick end class Human < ActiveRecord::Base has_many :dogs, :foreign_key => ‘owner_id’ acts_as_checkpoint model_may :pet model_allows :dogs, :to => :lick model_allows :dogs, :to => :bite, :unless => Proc.new { |human, dog, action| dog.owner == human } end owner = Human.new thug = Human.new dog = Dog.new( :owner => owner ) owner.can_pet?( dog ) => true thug.can_pet?( dog ) => false dog.can_lick?( dog ) => true dog.can_bite?( owner ) => false dog.can_bite?( thug ) => true






