module Can4::ControllerAdditions

Rails controller additions for Can4.

In most cases, it is not necessary to define anything here, as it is included for you automatically when ActionController::Base is defined.

However, if your controller resource is not defined using a method named current_user, or you use different arguments for your Ability constructor, you will need to override the current_ability method in your controller.

@example

class ApplicationController < ActionController::Base
  # ...

  private

  # This example shows a possible redefinition of current_ability
  # with a different scope and two constructor arguments.
  def current_ability
    @current_ability ||= ::Ability.new(current_admin, request.remote_ip)
  end
end

Public Class Methods

included(base) click to toggle source
# File lib/can4/controller_additions.rb, line 97
def self.included(base)
  base.extend ClassMethods

  return unless base.respond_to?(:helper_method)

  base.helper_method :can?, :cannot?, :current_ability
end

Public Instance Methods

authorize!(*args) click to toggle source

Raises a {Can4::AccessDenied} exception if the current ability cannot perform the given action. This is usually called in a controller action or before_action.

You can rescue from the exception in the controller to customize how unauthorized access is displayed.

@raise [Can4::AccessDenied]

The current ability cannot perform the requested action.
# File lib/can4/controller_additions.rb, line 66
def authorize!(*args)
  @_authorized = true
  current_ability.authorize!(*args)
end
can?(*args) click to toggle source

Use in the controller or view to check the resources's permission for a given action and object. This simply calls can? on the current ability.

@see Ability#can?

# File lib/can4/controller_additions.rb, line 85
def can?(*args)
  current_ability.can?(*args)
end
cannot?(*args) click to toggle source

Convenience method which works the same as {#can?}, but returns the opposite value.

@see Ability#cannot?

# File lib/can4/controller_additions.rb, line 93
def cannot?(*args)
  current_ability.cannot?(*args)
end
current_ability() click to toggle source

Creates and returns the current ability and caches it. If you want to override how the Ability is defined, then this is the place. Simply redefine the method in the controller to change its behavior.

Note that it is important to memoize the ability object so it is not recreated every time.

# File lib/can4/controller_additions.rb, line 77
def current_ability
  @current_ability ||= ::Ability.new(current_user)
end