假定系統中存在 developer
hacker
designer
startup
四種角色,且每種角色具獨立的權限需求。倘全部定義於ability.rb
則未免過於臃腫而不可讀。
基於角色維度進行ability.rb
的切分如下:
# app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.id.present?
self.merge Abilities::LoginedUserAbility.new(user)
self.merge Abilities.const_get("#{user.role}_ability".classify).new(user) if user.role.present?
else
self.merge Abilities::GuestAbility.new
end
end
end
# app/models/abilities/logined_user_ability.rb
module Abilities
class LoginedUserAbility
include CanCan::Ability
def initialize(user)
# ...
end
end
end
# app/models/abilities/developer_ability.rb
module Abilities
class DeveloperAbility
include CanCan::Ability
def initialize(user)
# ...
end
end
end
其餘角色同上
原文首發於我的博客 https://blog.boris.tech/posts/fu-za-luo-ji-xia-jie-ou-cancancan-de-ability-mo-xing