Ruby cancan

From wikinotes

Cancan is a framework for defining/granting/checking permissions for an ability.


WARNING:

cancan has been superceeded by cancancan

Documentation

official docs https://github.com/ryanb/cancan/wiki
github https://github.com/ryanb/cancan

Overview

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end

Permissions

Permissions are defined by pairing a permission, with a class.

can(:create, User)  # has permission to create User classes
can [:update, :destroy], [Article, Comment]

Permission Types

# single permissions
:create
:read
:update
:destroy

# group permissions
:manage  # all permissions

cancan defines these group permissions (ex. manage, read, ..) as can actions in their docs.

Object Types

can(:create, :all)  # can create any managed object
can(:create, User)  # can create instances of a class