使用 Pundit gem 导出所有用户策略

Export all user policies using Pundit gem

如何使用 Pundit Gem 检索所有用户策略和范围?我需要 return 一个包含所有用户策略的 json 对象来检查前端 javascript 模板中的权限。

使用 CanCanCan gem,我可以这样做:

class Ability
  include CanCan::Ability

  # ....

  def to_list
    rules.map do |rule|
      object = { actions: rule.actions, subject: rule.subjects.map{ |s| s.is_a?(Symbol) ? s : s.name } }
      object[:conditions] = rule.conditions unless rule.conditions.blank?
      object[:inverted] = true unless rule.base_behavior
      object
    end
  end
end

是否可以对 Pundit 做同样的事情?

我有同样的要求,根据调查我得到了以下代码:

def index
    classes = [Admin, BusNumber, Ticket, :ticket_statistics]     

    permissions = { }                             

    classes.each do |clazz|                       
        policy =  Pundit.policy(current_admin, clazz)      
        policy.public_methods(false).sort.each do |m|      
            result = policy.send m                    
            permissions["#{clazz}.#{m}"] = result     
        end
    end 

    render json: permissions
end  

current_admin是获取当前登录用户的方法,代码给出如下结果

{
    "Admin.create?": true,
    "Admin.disable?": true,
    "Admin.enable?": true,
    "Admin.index?": true,
    "Admin.show?": true,
    "Admin.update?": true,
    "BusNumber.create?": true,
    "BusNumber.destroy?": true,
    "BusNumber.index?": true,
    "BusNumber.update?": true,
    "Ticket.index?": true,
    "Ticket.refund_by_admin?": true,
    "Ticket.show?": true,
    "ticket_statistics.overall?": true
}