Module: Dry::Ability::Controller::Mixin

Extended by:
ActiveSupport::Concern
Included in:
Dry::Ability::Controller
Defined in:
lib/dry/ability/controller/mixin.rb

Instance Method Summary collapse

Instance Method Details

#authorize!(*args) ⇒ Object

Raises a Dry::Ability::AccessDenied exception if the current_ability cannot perform the given action. This is usually called in a controller action or before filter to perform the authorization.

def show
  @article = Article.find(params[:id])
  authorize! :read, @article
end

A :message option can be passed to specify a different message.

authorize! :read, @article, :message => "Not authorized to read #{@article.name}"

You can also use I18n to customize the message. Action aliases defined in Ability work here.

en:
  unauthorized:
    manage:
      all: "Not authorized to %{action} %{subject}."
      user: "Not allowed to manage other user accounts."
    update:
      project: "Not allowed to update this project."

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

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end
end

See the CanCan::AccessDenied exception for more details on working with the exception.

See the load_and_authorize_resource method to automatically add the authorize! behavior to the default RESTful actions.



50
51
52
53
# File 'lib/dry/ability/controller/mixin.rb', line 50

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

#can?(*args) ⇒ Object

See Also:

  • Mixin#can?


72
# File 'lib/dry/ability/controller/mixin.rb', line 72

delegate :can?, to: :current_ability

#cannot?(*args) ⇒ Object

See Also:

  • Mixin#cannot?


76
# File 'lib/dry/ability/controller/mixin.rb', line 76

delegate :cannot?, to: :current_ability

#current_abilityObject

Creates and returns the current user’s ability and caches it. If you want to override how the Ability is defined then this is the place. Just define the method in the controller to change behavior.

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

Notice it is important to cache the ability object so it is not recreated every time.



66
67
68
# File 'lib/dry/ability/controller/mixin.rb', line 66

def current_ability
  @current_ability ||= ability_class.new(current_user)
end