简体   繁体   English

CanCan和能力阻挡

[英]CanCan and ability block

I have this piece of code that defines CanCan's user permissions, but I don't understand what the conditions inside the block are for ? 我有这段代码定义了CanCan的用户权限,但是我不明白该块内的条件是什么?

    class Ability
          include CanCan::Ability

          def initialize(user)

            user.permissions.each do |permission|
              can permission.action.to_sym,
              permission.thing_type.constantize do |thing|
               thing.nil? || permission.thing_id.nil? || permission.thing_id == thing.id
              end
            end


end
end

So, this lines of code are bugging me: 因此,这行代码困扰着我:

permission.thing_type.constantize do |thing|
       thing.nil? || permission.thing_id.nil? || permission.thing_id == thing.id
end

I understand that block is used to define complex conditions and I guess that permission.thing_id == thing.id is there so that permission is granted only for selected objects but I don't see the purpoose of thing.nil? || permission.thing_id.nil? 我知道该块用于定义复杂的条件,并且我猜到那是permission.thing_id == thing.id ,因此仅对选定的对象授予许可,但我看不到thing.nil的thing.nil? || permission.thing_id.nil? thing.nil? || permission.thing_id.nil? .What's that for? 。那个有什么用途?

So, according to the CanCan docs , when you pass a block to can (which is what's going on here), the permission is given only if the block returns true. 因此, 根据CanCan docs ,当您将一个块传递给can (这就是这里发生的事情),仅当该块返回true时,才授予权限。 The object passed in to the block is the object that the user might have permission to do something to. 传递给块的对象是用户可能有权执行操作的对象。

What this does, then, is give the user permission to perform permission.action on the class permission.thing_type if: 然后,如果发生以下情况,则向用户授予对类permission.thing_type执行permission.actionpermission.thing_type

  1. thing is nil. thing是零。 This might happen in the case of things like create permission, which doesn't take a specific object (it takes the class instead). 这可能发生在诸如create权限之类的情况下,该权限不使用特定对象(而是使用类)。
  2. permission.thing_id is nil. permission.thing_id为零。 This is dealing with the case where the Permission object doesn't point at a specific thing. 这是在处理Permission对象没有指向特定事物的情况。 This feels like the opposite side of item 1. It might apply in the case of 'blanket' permissions - a permission that says a particular user can perform this action on any object of this class. 感觉就像项目1的反面。它可能适用于“空白”权限-这种权限表示特定用户可以对此类的任何对象执行此操作。 OR 要么
  3. The thing has the id specified in the permission object. thing具有在权限对象中指定的ID。

Moral: Comment your code. 道德:注释您的代码。 Even if it's obvious to you right now what something does, it might not be to the next person. 即使现在对您很明显,有些事情在做什么,但对下一个人来说可能就不是。 Who might also be you, in a few months. 几个月后,谁可能也是你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM