Module: Can4::ControllerAdditions

Defined in:
lib/can4/controller_additions.rb

Overview

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.

Examples:

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

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#authorize!(*args) ⇒ Object

Raises a 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.

Raises:


66
67
68
69
# File 'lib/can4/controller_additions.rb', line 66

def authorize!(*args)
  @_authorized = true
  current_ability.authorize!(*args)
end

#can?(*args) ⇒ Boolean

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.

Returns:

  • (Boolean)

See Also:


85
86
87
# File 'lib/can4/controller_additions.rb', line 85

def can?(*args)
  current_ability.can?(*args)
end

#cannot?(*args) ⇒ Boolean

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

Returns:

  • (Boolean)

See Also:


93
94
95
# File 'lib/can4/controller_additions.rb', line 93

def cannot?(*args)
  current_ability.cannot?(*args)
end

#current_abilityObject

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.


77
78
79
# File 'lib/can4/controller_additions.rb', line 77

def current_ability
  @current_ability ||= ::Ability.new(current_user)
end