ruby-on-rails – Rails CanCan宝石重构能力类

我的轨道应用程序中有13个模型,我使用所有这些模型.我的能力不断增加.我对不同的CRUD操作有不同的能力条件,这使得它难以管理.

有人可以指导我怎么可以重构这个..?喜欢,使用模块或类使我的能力类看起来整洁.

解决方法

简单的escateario:如果您可以将权限拆分为多个互斥的集合,那么您应该从@ryanb,CanCan创建者检查此提案,将其中的能力分解为几个不同的类,然后覆盖ApplicationController中的current_ability方法

How you can break up large Ability class in CanCan – Gists

更复杂的场景:如果您有几个不同的重叠权限集,您可以尝试这种方法

# app/models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    self.merge Abilities::Everyone.new(user)

    if user
      self.merge Abilities::Admin.new(user) if user.admin?
      self.merge Abilities::Authenticated.new(user)
    else
      self.merge Abilities::Guest.new(user)
    end
  end
end

# app/models/abilities/admin.rb
module Abilities
  class Admin
    include CanCan::Ability

    def initialize(user)
      # define abilities here ...
    end
  end
end

# app/models/abilities/everyone.rb
...

对于其余的文件,依此类推.

有关文档的更多信息.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...