Cancan abilities in a separate file

Is it possible to define capabilities in a separate file and include them in the .rb file inside the initialize method?

the code below returns: try and got: undefined method 'can'

ability.rb

def initialize(user) include MyExtension::Something::CustomAbilities ... end 

Library / my_extension / something.rb

 module MyExtension::Something module CustomAbilities can :do_it, Project do |project| check_something_here and return true or false... end end end 

the ideal solution, if possible, would be to extend the class Ability with Ability.send: include / extend, so without explicitly including it in the initialize method

+2
ruby ruby-on-rails cancan
source share
1 answer

Just turn on the module and call the method in initialize

The trick here is to create modules for each of your abilities, include them in your base ability.rb file, and then run a specific method in your initialize method, for example:

In your ability.rb file:

 class Ability include CanCan::Ability include ProjectAbilities def initialize user # Your "base" abilities are defined here. project_abilities user end end 

In your lib/project_abilities.rb file:

 module ProjectAbilities def project_abilities user # New abilities go here and later get added to the initialize method # of the base Ability class. can :read, Project do |project| user.can? :read, project.client || user.is_an_admin? end end end 

Using this template, you can break down your abilities into different modules (perhaps one for each model for which you must determine the user's capabilities).

Take a look at Pundit

Also, take a look at the (relatively) new gem called Pundit , which provides a much more scalable template for authorizing larger sites.

Greetings

In JP

+3
source share

All Articles