public
Description: Rails plugin for generating role- and association-based permission checks on controllers and ActiveRecord models.
Home | Edit | New

For ActiveRecord-based models

Out of the box, acts_as_checkpoint supports association-based permission checks.

class User < ActiveRecord::Base has_many :robot_overlords acts_as_checkpoint model_may :view, :edit, :destroy, :eat, :drink model_allows :self, :to => [ :view, :edit, :destroy ] model_allows :robot_overlords, :to => :destroy end

The model_may call will create several instance methods:


  • User#can_view?( target )

  • User#can_edit?( target )

  • User#can_destroy?( target )

  • User#can_eat?( target )

  • User#can_drink?( target )

The model_allows call will also generate some instance methods:


  • User#allows_view_by?( actor )

  • User#allows_edit_by?( actor )

  • User#allows_destroy_by?( actor )

These methods can then be used in controllers and views anywhere you need to check permissions.

To incorporate role-based permission checks, your actor models will need to expose “role check” methods indicating membership in each individual role — e.g., “admin?” and “registered_user?.” Simply refer to these methods as you would any association in your model_allows calls.

class RobotOverlord has_many :robot_over_overlords acts_as_checkpoint model_may :incinerate model_allows :deactivate, :by => [ :admin?, :robot_over_overlords ] end

For even finer-grained control of permissions, model_allows will accept :if and/or :unless parameters. They take a Proc or method name, and do exactly what their names imply. Even if an actor passes the role/association check, it must still pass any :if and :unless checks specified.

class Cheese acts_as_state_machine :initial => :block state :block, :melted, :shredded event melt do transitions :from => :block, :to => :melted end event shred do transitions :from => :block, :to => :shredded end acts_as_checkpoint model_allows :eat, :unless => Proc.new { |cheese, actor, action| cheese.moldy? || actor.lactose_intolerant? } model_allows [ :melt, :shred ], :if => :ready_for_action? def ready_for_action?( actor, action ) next_events_for_state( current_state ).include?( action ) end end

The Proc/method given as each :if/:unless parameter’s value is passed three parameters, to provide maximum logic flexibility.


  • target — the target of the action

  • actor — the source of the action

  • action — name of the action being checked (I’ve found this useful for models with acts_as_state_machine)
Last edited by blangenfeld, Thu Aug 14 00:22:45 -0700 2008
Home | Edit | New
Versions: