康康能力在单独的文件中 [英] cancan abilities in separate file

查看:59
本文介绍了康康能力在单独的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在单独的文件中定义能力并将其包含在初始化方法中的capability.rb文件中?

Is it possible to define abilities in separate file and include them in ability.rb file inside initialize method ?

以下代码返回:try and got:undefined method'可以

belowed code returns: tried and got: undefined method 'can'

ability.rb

ability.rb

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

lib / my_extension / something.rb

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:include / extend扩展Ability类,因此在初始化方法中无需显式包含

perfect solution, if possible, would be to extend class Ability with Ability.send :include/extend, so without explicit include in initialize method

推荐答案

只需在初始化



<中包含模块并调用方法

这里的窍门是为每个能力创建模块,将它们包含在基本的文件中,然后在初始化方法,如下所示:

Just Include the Module and Call the Method in initialize

The trick here is to create modules for each of your abilities, include them in your base ability.rb file and then run the specific method in your initialize method, like so:

在您的 ability.rb 文件:

In your ability.rb file:

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 文件中:

In your lib/project_abilities.rb file:

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

使用此功能模式,您可以将您的能力分解为多个模块(也许,每个模型都必须定义一个功能)。

Using this pattern, you can break out your abilities into various modules (perhaps, one for each model that you have to define user abilities for).

另外请注意,请看一下(相对)名为 Pundit 的新宝石,它为大型站点的授权提供了更具可扩展性的模式。

Also of note, take a look at the (relatively) new gem called Pundit, which provides a much more scalable pattern for authorization of larger sites.

干杯,

JP

这篇关于康康能力在单独的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆