【问题标题】:cancan abilities in separate filecancan 能力在单独的文件中
【发布时间】:2011-10-12 10:05:47
【问题描述】:

是否可以在单独的文件中定义能力并将它们包含在 initialize 方法中的能力.rb 文件中?

下面的代码返回:尝试并得到:未定义的方法'can'

能力.rb

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

lib/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

如果可能的话,完美的解决方案是使用 Ability.send 扩展类 Ability :include/extend,因此在初始化方法中无需显式包含

【问题讨论】:

  • 嘿@artur79,其中一个答案对您有用吗,还是您找到了自己的解决方案?请将其中一个答案标记为正确或发布您自己的解决方案。谢谢!

标签: ruby-on-rails ruby cancan


【解决方案1】:

只需包含模块并调用initialize中的方法

这里的诀窍是为您的每个能力创建模块,将它们包含在您的基本 ability.rb 文件中,然后在您的 initialize 方法中运行特定方法,如下所示:

在您的ability.rb 文件中:

class Ability

  include CanCan::Ability

  include ProjectAbilities 

  def initialize user
    # Your "base" abilities are defined here.

    project_abilities user
  end  

end

在您的lib/project_abilities.rb 文件中:

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

使用这种模式,您可以将您的能力分解为不同的模块(也许,每个模块一个,您必须为其定义用户能力)。

看看Pundit

另外值得注意的是,看看名为Pundit 的(相对)新的gem,它为大型网站的授权提供了更具可扩展性的模式。

干杯,

日本

【讨论】:

    【解决方案2】:

    使用更现代的红宝石,您可以通过prepend 实现这一目标

    module CashBalance
      attr_accessor :balance
    
      def deposit(amount)
        self.balance += amount
      end
    
      def withdraw(amount)
        self.balance -= amount
      end
    
      def initialize(*args)
        self.balance = 0.0
        super
      end  
    
    end
    
    class Bank
      prepend CashBalance
    
      def initialize(name)
        @name = name
      end
    
      def dump
        puts "%s has a balance of %0.2f" % [ @name, balance ]
      end
    
    
    end
    
    
    b = Bank.new("Fleet")
    
    b.deposit(20)
    b.dump
    b.withdraw(10)
    b.dump
    

    产量

    $ ruby blarg.rb
    Fleet has a balance of 20.00
    Fleet has a balance of 10.00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多