本站首页    管理页面    写新日志    退出


«September 2025»
123456
78910111213
14151617181920
21222324252627
282930


公告
 本博客在此声明所有文章均为转摘,只做资料收集使用。

我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:
日志总数:1304
评论数量:2242
留言数量:5
访问次数:7621973
建立时间:2006年5月29日




[Ruby on Rails]简单的角色权限检查插件
软件技术

lhwork 发表于 2007/2/8 10:10:38

代码比较简单: module ActionController #:nodoc:  class CheckGroupError < ActionControllerError #:nodoc:    attr_reader :group_name    def initialize(group_name)      @group_name = group_name    end  end    class CheckRoleError < ActionControllerError #:nodoc:    attr_reader :role_name    def initialize(role_name)      @role_name = role_name    end  end    class Base #:nodoc:    def roles      []    end        def groups      []    end        def check_roles(*role_args)      role_args.each do |role|        check_role(role)      end    end        def check_groups(*group_args)      group_args.each do |group|        check_group(group)      end    end        def check_group(group)      raise CheckGroupError.new(group.to_s) unless groups().include?(group.to_s)    end        def check_role(role)      raise CheckRoleError.new(role.to_s)   unless roles().include?(role.to_s)          end  end  end只需要在ApplicationController中实现roles和groups这2个方法,对数据库模式没有任何限制,只要能保证这2个方法能够得到当前用户的角色和组即可。有4个check方法可用,可任意使用一个或多个。简单模拟测试一下: class ApplicationController < ActionController::Base  def roles    %w(add show)  end  def groups    %w(users)  endend class TestController < ApplicationController  def test1    check_role :add    render_text "OK"  end  def test2    check_role :add    check_group :users    render_text "OK"  end  def test3    check_groups :admin, :users    render_text "OK"  end  def test4    check_roles :add, :remove    render_text "OK"  endend其中,test1、test2都会成功,而test3和test4则会失败显示异常,只需要处理rescue_action把它修改为自己的显示页面即可。


阅读全文(2163) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.063 second(s), page refreshed 144788348 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号