No commit activity in last 3 years
No release in over 3 years
Add namespace for cancan authorization library
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

>= 1.6.3
 Project Readme

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 © 2011 Aimbulance, released under the MIT license