Advertisement
Guest User

Untitled

a guest
May 25th, 2015
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. # This concern enables namespaces in Pundit. In order to use it, put this
  2. # module into the `app/controllers/concerns` folder of your project and then
  3. # include the module into the controller you want to namespace the policies in
  4. # after the include of Pundit.
  5. #
  6. # To secify the namespace to use, overwrite the `pundit_namespace` method on
  7. # your controller then.
  8. #
  9. # Example
  10. # =======
  11. #
  12. # ```ruby
  13. # class API::V3::BaseController < ApplicationController
  14. # include Pundit
  15. # include Concerns::PunditNamespaces
  16. #
  17. # def pundit_user
  18. # current_user
  19. # end
  20. #
  21. # def pundit_namespace
  22. # V3
  23. # end
  24. # end
  25. # ```
  26. #
  27. # In order to re-implement as few things as possible, the policies and the
  28. # scopes are resolved by Pundit::PolicyFinder which returns the resolved class
  29. # without a namespace. Therefor a dummy policy without a namespace has to
  30. # exist, otherwise you will get a class not found exception.
  31. #
  32. module Concerns::PunditNamespaces
  33. def self.included(receiver)
  34. receiver.send :include, InstanceMethods
  35. end
  36.  
  37. module InstanceMethods
  38. # To set the namespace, overwrite this method in your controller
  39. def pundit_namespace
  40. Object
  41. end
  42.  
  43. def policies
  44. NamespacedPolicyFinder.new(pundit_user, pundit_namespace)
  45. end
  46.  
  47. def policy_scopes
  48. NamespacedPolicyScopeFinder.new(pundit_user, pundit_namespace)
  49. end
  50. end
  51.  
  52. class NamespacedPolicyFinder
  53. def initialize(user, namespace)
  54. @user = user
  55. @namespace = namespace
  56. end
  57.  
  58. def policies
  59. @_policies ||= {}
  60. end
  61.  
  62. def [](object)
  63. policies[object] ||= begin
  64. policy = Pundit::PolicyFinder.new(object).policy
  65. policy = "#{@namespace}::#{policy.to_s}".constantize
  66. policy.new(@user, object)
  67. end
  68. end
  69. end
  70.  
  71. class NamespacedPolicyScopeFinder
  72. def initialize(user, namespace)
  73. @user = user
  74. @namespace = namespace
  75. end
  76.  
  77. def policy_scopes
  78. @_policy_scopes ||= {}
  79. end
  80.  
  81. def [](object)
  82. policy_scopes[object] ||= begin
  83. policy = Pundit::PolicyFinder.new(object).scope
  84. policy = "#{@namespace}::#{policy.to_s}".constantize
  85. policy.new(@user, object).resolve
  86. end
  87. end
  88. end
  89. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement