一旦能力定义的数量开始增加,处理能力文件就变得越来越困难。
按照以下示例,处理这些问题的第一个策略是将能力转移到有意义的方法中:
class Ability include CanCan::Ability def initialize(user) anyone_abilities if user if user.admin? admin_abilities else authenticated_abilities end else guest_abilities end end private def anyone_abilities # 为每个人定义能力,包括登录用户和访问者 end def guest_abilities # 为访客定义能力 end def authenticated_abilities # 仅为登录用户定义功能 end def admin_abilities # 仅为管理员定义功能 end end
一旦此类足够大,您可以尝试将其分为不同的类以处理不同的职责,如下所示:
# app / models / ability.rb class Ability include CanCan::Ability def initialize(user) self.mergeAbilities::Everyone.new(user) if user if user.admin? self.mergeAbilities::Admin.new(user) else self.mergeAbilities::Authenticated.new(user) end else self.mergeAbilities::Guest.new(user) end end end
然后将这些类定义为:
# 应用/模型/功能/guest.rb module Abilities class Guest include CanCan::Ability def initialize(user) # 仅适用于匿名访问者的能力 end end end
等等Abilities::Authenticated,Abilities::Admin或其他。