Ruby CanCanCan 动态定义方法

灵感来自这里https://github.com/kristianmandrup/cantango/wiki/CanCan-vs-CanTango

如果权限不多,我们可以通过这种方式来定义

ruby 复制代码
class CanCan::Ability
  def initialize user, options = {}
    if !user
      can :read, :all
    end
    if user
      admin_rules if user.roles.include? :admin
      editor_rules if user.roles.include? :editor
      default_rules
    end
  end

  def admin_rules
    can :manage, :all
  end

  def editor_rules
    can :manage, [Article, Post]
  end
end

改的灵活点

ruby 复制代码
class CanCan::Ability
  def initialize user, options = {}
    user ? user_rules : guest_user_rules
  end

  def user_rules
    user.roles.each do |role|
      exec_role_rules(role) if user.roles.include? role
    end
    default_rules
  end

  def exec_role_rules role
    meth = :"#{role}_rules"
    send(meth) if respond_to? meth
  end
  
  # various rules methods for each role
  def admin_rules
    can :manage, :all
  end

  def editor_rules
    can :manage, [Article, Post]
  end
  ...

  def default_rules
    can :read, :all
  end
end

上面是原文出处,实际使用的时候还是不方便,我改成这样了(非一比一还原)。使用define_method 定义那个每个方法:

ruby 复制代码
class Ability
  include CanCan::Ability

  @@permissions = xxx
  def initialize(user)
    @user= user|| User.new
    @user.roles.each do |role|
       exec_role_rules(role) if @user.has_role?(role)
    end
  end

  Role.all.each do |role|
    define_method "rules_#{role.name.gsub(" ", "_")}" do
      role_permissions = RolePermission.where(role_id: role.id)
      unless role_permissions.blank?
        role_permissions.each do |rp|
          permission_value = @@permissions[rp.permission_key]
          entities = permission_value["entities"].map{|e| e.constantize}
          actions = permission_value["actions"].map{|e| e.to_sym}
          can actions, entities
        end
      end
    end
  end

  def exec_role_rules(role)
    meth = :"rules_#{role.name.gsub(" ", "_")}"
    send(meth) if respond_to? meth
  end

end

经测试嘎嘎好用,就是我还需要添加一些条件筛选,导致我这个不能用,得删掉,有点可惜,记录一下~

相关推荐
虾球xz9 分钟前
CppCon 2018 学习:THE MOST VALUABLE VALUES
开发语言·c++·学习
阿蒙Amon1 小时前
C#扩展方法全解析:给现有类型插上翅膀的魔法
开发语言·c#
尘浮7281 小时前
60天python训练计划----day59
开发语言·python
Chef_Chen2 小时前
从0开始学习R语言--Day39--Spearman 秩相关
开发语言·学习·r语言
不学会Ⅳ2 小时前
Mac M芯片搭建jdk源码环境(jdk24)
java·开发语言·macos
好开心啊没烦恼3 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas
lljss20204 小时前
Python11中创建虚拟环境、安装 TensorFlow
开发语言·python·tensorflow
Python×CATIA工业智造7 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
我叫小白菜8 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
狐凄8 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python