Module: CanCan::ControllerAdditions

Defined in:
lib/cancan/controller_additions.rb

Overview

This module is automatically included into all controllers. It also makes the “can?” and “cannot?” methods available to all views.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



113
114
115
116
# File 'lib/cancan/controller_additions.rb', line 113

def self.included(base)
  base.extend ClassMethods
  base.helper_method :can?, :cannot?
end

Instance Method Details

#can?(*args) ⇒ Boolean

Use in the controller or view to check the user’s permission for a given action and object.

can? :destroy, @project

You can also pass the class instead of an instance (if you don’t have one handy).

<% if can? :create, Project %>
  <%= link_to "New Project", new_project_path %>
<% end %>

This simply calls “can?” on the current_ability. See Ability#can?.

Returns:

  • (Boolean)


168
169
170
# File 'lib/cancan/controller_additions.rb', line 168

def can?(*args)
  (@current_ability ||= current_ability).can?(*args)
end

#cannot?(*args) ⇒ Boolean

Convenience method which works the same as “can?” but returns the opposite value.

cannot? :destroy, @project

Returns:

  • (Boolean)


176
177
178
# File 'lib/cancan/controller_additions.rb', line 176

def cannot?(*args)
  (@current_ability ||= current_ability).cannot?(*args)
end

#current_abilityObject

Creates and returns the current user’s ability. You generally do not invoke this method directly, instead you can override this method to change its behavior if the Ability class or current_user method are different.

def current_ability
  UserAbility.new() # instead of Ability.new(current_user)
end


152
153
154
# File 'lib/cancan/controller_additions.rb', line 152

def current_ability
  ::Ability.new(current_user)
end

#unauthorized!(message = "You are not authorized to access this page.") ⇒ Object

Raises the CanCan::AccessDenied exception. This is often used in a controller action to mark a request as unauthorized.

def show
  @article = Article.find(params[:id])
  unauthorized! if cannot? :read, @article
end

The unauthorized! method accepts an optional argument which sets the message of the exception.

You can rescue from the exception in the controller to define the behavior.

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = exception.message
    redirect_to root_url
  end
end

See the load_and_authorize_resource method to automatically add the “unauthorized!” behavior to a RESTful controller’s actions.

Raises:



140
141
142
# File 'lib/cancan/controller_additions.rb', line 140

def unauthorized!(message = "You are not authorized to access this page.")
  raise AccessDenied, message
end