pundit的使用ruby on rails

保姆级入门ruby 

http://ruby.zhihuichina.net.cn

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?

结束
 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值