您的位置:首页 > 编程语言 > Ruby

pundit的使用ruby on rails

2017-07-31 21:23 369 查看

pundit的安装和配置start

在gemfile中添加# gem pundit

在命令行输入# bundle install

在ApplicationController中# include Pundit

在命令行输入# rails g pundit:install

打开config/application.rb 添加代码 # config.autoload_paths += %W[#{config.root}/app/policies]

pundit的安装和配置end

看到这里实际上pundit已经配置完成了,我们可以在rails c 中进行一下测试。

irb(main):001:0> ApplicationPolicy  #=> ApplicationPolicy   如果是这样的就是正确的了。

下面是如何使用

Pundit给我的感觉非常的直观在application_policy.rb文件中就是一个干干净净的ruby的类没有引入和继承。

attr_reader :user, :record #=> user就是当前用户,record对应的就是数据库模型

在这里我们把他当作变量就好了。

def initialize(user, record)

  @user = user

  @record = record

end

再往下我们会看到

def index?

  false

end

这样的方法,特别直观。index就对应我们controller的index,这个方法返回的是false就是没有权限,是true就是有权限。

和rails一样pundit也有约定俗成一些名字。

比如rails的模型名字和数据库的表名字是相同的。

同样pundit的名字(app/policies/user_policy.rb)和rails的模型名字(user.rb)是相同的。

举个使用的例子,在user_policy.rb中定义个一个方法

def edit?

 false

end 

那么在users_controller.rb的edit方法中

def edit

  @what = User.find params[:id]

  authorize @what

end

这样就可以使用了。

有必要说一下,authorize 后面可以传递两个参数, 第二个参数为自定义参数。

比如 authorize @what , :if_edit?

那么 在user_policy.rb就可以自定义 :

def if_edit?

  true

end

在view中使用pundit

<%  if policy(???).edit?  %>

<%  end  %>

如果我们默认用户不是current_user的话我们可以自己定义一个私有方法

private

def pundit_user

   当前的user。

end

在对应的模型中也可以自定义约束

def self.policy_class

  ManagerPolicy

end

如果没有权限访问会抛出异常。抓取异常

rescue_from Pundit::NotAuthorizedError, with: :not_authorized

private

def not_authorized

  render plain: 'not authorized', status: 403

end

如果和数据操作没有任何关系的时候,我们可以自定义policy类来进行引入操作

比如创建一个general_policy.rb   定义了方法is_true?

调用:Pundit.policy(User.last, :general).is_true?

结束

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: