Get a string that represents a user's CanCan abilities

前端 未结 2 1716
名媛妹妹
名媛妹妹 2021-02-01 10:07

I want to cache a Post view, but the view depends on the permissions of the current user (e.g., I only show the \"edit\" link if current_user.can?(:edit, @pos

2条回答
  •  时光取名叫无心
    2021-02-01 10:31

    EDIT: revised for CanCanCan

    As of version 1.12 of CanCanCan (the community continuation of CanCan), Ability.new(user).permissions returns a hash with all permissions for the given user.

    Previous answer (CanCan):

    This might be a little complex...but here it goes..

    If you pass the specified User into the Ability model required by CanCan, you can access the definition of that users role using instance_variable_get, and then break it down into whatever string values you want from there..

    >> u=User.new(:role=>"admin")
    >> a=Ability.new(u)
    >> a.instance_variable_get("@rules").collect{ 
          |rule| rule.instance_variable_get("@actions").to_s
       }
    => ["read", "manage", "update"]
    

    if you want to know the models in which those rules are inflicted upon, you can access the @subjects instance variable to get its name..

    here is the model layout for Ability from which I worked with (pp)

    Ability:0x5b41dba @rules=[
      #, 
      #, 
      #4}, 
        @match_all=false, 
        @block=nil, 
        @subjects=[
          User(role: string)]>
    ]
    

提交回复
热议问题