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.
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
-
#authorize!(*args) ⇒ Object
Raises a AccessDenied exception if the current ability cannot perform the given action.
-
#can?(*args) ⇒ Boolean
Use in the controller or view to check the resources’s permission for a given action and object.
-
#cannot?(*args) ⇒ Boolean
Convenience method which works the same as #can?, but returns the opposite value.
-
#current_ability ⇒ Object
Creates and returns the current ability and caches it.
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.
66 67 68 69 |
# File 'lib/can4/controller_additions.rb', line 66 def (*args) @_authorized = true current_ability.(*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.
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.
93 94 95 |
# File 'lib/can4/controller_additions.rb', line 93 def cannot?(*args) current_ability.cannot?(*args) end |
#current_ability ⇒ Object
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 |