Guest User

Untitled

a guest
Feb 19th, 2018
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. module Securable
  2. def self.included(base)
  3. base.extend(ClassMethods)
  4. end
  5. class Secured
  6. def initialize(p, o)
  7. @o = o
  8. @o.class.methods_with_permissions(p) {|m| define_proxy_method(m)}
  9. end
  10.  
  11. def self.is_permission_match?(p, min_p)
  12. case min_p
  13. when :guest
  14. true
  15. when :admin
  16. (p == :admin)
  17. when :owner
  18. (p == :admin || p == :owner)
  19. else
  20. false
  21. end
  22. end
  23.  
  24. private
  25.  
  26. def define_proxy_method(m)
  27. (class << self; self; end).class_eval do
  28. define_method m do |*args|
  29. @o.send m, *args
  30. end
  31. end
  32. end
  33. end
  34. module ClassMethods
  35. def methods_with_permissions(p)
  36. (@method_permissions ||= {}).each do |k, v|
  37. yield k if Securable::Secured.is_permission_match?(p, v)
  38. end
  39. nil
  40. end
  41. private
  42. def attr_accessor_secure(p, *args)
  43. args.each do |a|
  44. require_permissions_for_method(a, p)
  45. attr_reader a
  46. end
  47. end
  48.  
  49. def require_permissions_for_method(m, p)
  50. (@method_permissions ||= {})[m] = p
  51. end
  52. end
  53. end
  54.  
  55. class User
  56. include Securable
  57. attr_accessor_secure :guest, :username
  58. attr_accessor_secure :owner, :email, :password
  59. attr_accessor_secure :admin, :role
  60. end
  61.  
  62. u = User.new
  63. u.username = 'kurt'
  64. u.password = 'test'
  65. u.email = 'kurt@mubble.net'
  66.  
  67. s = User::Secured.new(:guest, u)
Add Comment
Please, Sign In to add comment