Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How you can break up large Ability class in CanCan
module Abilities
def self.ability_for(user)
if user.admin?
AdminAbility.new(user)
else user
MemberAbility.new(user)
else
GuestAbility.new
end
end
class AdminAbility
include CanCan::Ability
def initialize(user)
# ...
end
end
class MemberAbility
include CanCan::Ability
def initialize(user)
# ...
end
end
class GuestAbility
include CanCan::Ability
def initialize(user)
# ...
end
end
# move classes into separate files as needed if they get too long
end
def current_ability
@current_ability ||= Abilities.ability_for(current_user)
end
@jmuheim

This comment has been minimized.

Copy link

@jmuheim jmuheim commented Feb 28, 2014

Where do you put this file?

@dgilperez

This comment has been minimized.

Copy link

@dgilperez dgilperez commented Aug 6, 2014

Thanks for this! How would you do if some permissions are not mutually exclusive - i.e. a User has different roles? For example, an Admin should have permissions defined in AdminAbility and also the ones in MemberAbility.

@jaredbeck

This comment has been minimized.

Copy link

@jaredbeck jaredbeck commented Apr 13, 2015

How would you do if some permissions are not mutually exclusive ..?

An example from @dgilperez using Ability#merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment