class Policy
Attributes
action[R]
model[R]
user[R]
Public Class Methods
new(model:, user: @model = model)
click to toggle source
# File lib/clean-policy/base.rb, line 4 def initialize model:, user: @model = model @user = user || current_user end
Public Instance Methods
can()
click to toggle source
# File lib/clean-policy/base.rb, line 25 def can Proxy.new self end
can?(action, *args, &block)
click to toggle source
pass block if you want to handle errors yourself return true if false if block is passed
# File lib/clean-policy/base.rb, line 11 def can? action, *args, &block @action = action .to_s .gsub(/[^\w+]/, '') .concat('?') .to_sym # pre check raise RuntimeError, 'Method name not allowed' if %i(can).index(@action) raise NoMethodError, %[Policy check "#{@action}" not found in #{self.class}] unless respond_to?(@action) call *args, &block end
Private Instance Methods
before(action)
click to toggle source
# File lib/clean-policy/base.rb, line 51 def before action false end
call(*args, &block)
click to toggle source
call has to be isolated because specific of error handling
# File lib/clean-policy/base.rb, line 32 def call *args, &block raise Error, 'User is not defined, no access' unless @user return true if before(@action) return true if send(@action, *args) raise Error, 'Access disabled in policy' rescue Policy::Error => error message = error.message message += " - #{self.class}.#{@action}" if block block.call(message) false else raise Policy::Error, message end end
current_user()
click to toggle source
get current user from globals if globals defined
# File lib/clean-policy/base.rb, line 60 def current_user if defined?(User) && User.respond_to?(:current) User.current elsif defined?(Current) && Current.respond_to?(:user) Current.user else raise RuntimeError.new('Current user not found in Policy#current_user') end end
error(message)
click to toggle source
# File lib/clean-policy/base.rb, line 55 def error message raise Policy::Error.new(message) end