cancan_namespace

Add namespace for cancan authorization library

MIT License

Downloads
31.7K
Stars
5
Committers
2

= CancanNamespace

Namespace for cancan gem.

== Install

gem 'cancan_namespace'

== Usage

class Ability include CanCanNamespace::Ability

def initialize(user)
  
  ...
  
  if user.admin?
    can :manage, :all
    can :manage, :all, :context => :manage
  end
end

end

=== Controller

Context is extracted from controller name (:manage):

class Manage::PostsController < Manage::BaseController before_filter :find_post, :only => [:edit, :update, :destroy] authorize_resource ... end

Set context for controller directly:

class People::RelationshipsController < Account::BaseController before_filter :find_followed before_filter :build_relation, :only => [:create] before_filter :find_relationship, :only => [:destroy]

authorize_resource :relationship, :context => :account

...

end

=== View

If no extra context argument is given, it defaults to the namespace where the current controller lives

app/views/posts/show.html.erb

controller has no namespace -> context = nil

<% if can? :edit, post %> <%= link_to 'Edit', edit_post_path(post) %> <% end %>

When you want to check an ability for another context, specify it manually

app/views/posts/show.html.erb

<% if can? :edit, post, :context => :manage %> <%= link_to 'Edit (admin)', edit_manage_post_path(post) %> <% end %>

When the current controller is in a namespace and you want to check an ability for the nil context, meaning a controller without namespace, you need to specify context => nil

app/views/manage/posts/show.html.erb

controller has namespace "manage" -> context is manually overridden to nil

<% if can? :edit, post, :context => nil %> <%= link_to 'Edit', edit_post_path(post) %> <% end %>

Copyright (c) 2011 Aimbulance, released under the MIT license