class Policy
Attributes
action[R]
model[R]
user[R]
Public Class Methods
can(model=nil, user=nil)
click to toggle source
convenient proxy access
# File lib/egoist/proxy.rb, line 4 def can model=nil, user=nil if model.is_a?(Hash) model, user = model[:model], model[:user] end klass = self # if we are calling can on Policy class, figure out policy name or fall back to ModelPolicy if self == Policy klass = ('%s_policy' % model.class).classify klass = Object.const_defined?(klass) ? klass.constantize : ::ModelPolicy end klass.new(user: user, model: model).can end
error(msg)
click to toggle source
# File lib/egoist/error.rb, line 8 def error msg raise ::Policy::Error.new(msg) end
new(model:, user: nil)
click to toggle source
# File lib/egoist/base.rb, line 4 def initialize model:, user: nil @model = model @user = user || current_user end
Public Instance Methods
can()
click to toggle source
# File lib/egoist/base.rb, line 30 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/egoist/base.rb, line 11 def can? action, *args, &block @action = action .to_s .gsub(/[^\w+]/, '') .concat('?') .to_sym # pre check if %i(can).index(@action) raise RuntimeError.new('Method name not allowed') end unless respond_to?(@action) raise NoMethodError.new(%[Policy check "#{@action}" not found in #{self.class}]) end call *args, &block end
error(message)
click to toggle source
# File lib/egoist/error.rb, line 15 def error message raise Policy::Error.new(message) end
Private Instance Methods
after(action)
click to toggle source
# File lib/egoist/base.rb, line 60 def after action true end
before(action)
click to toggle source
# File lib/egoist/base.rb, line 56 def before action false end
call(*args, &block)
click to toggle source
call has to be isolated because specific of error handling
# File lib/egoist/base.rb, line 37 def call *args, &block error 'User is not defined, no access' unless @user return true if before(@action) == true return true if send(@action, *args) && after(@action) == true error 'Access disabled in policy' rescue Policy::Error => error message = error.message message += " - #{self.class}##{@action}" if block block.call(message) false else error message end end
current_user()
click to toggle source
get current user from globals if globals defined
# File lib/egoist/base.rb, line 65 def current_user if defined?(User) && User.respond_to?(:current) User.current elsif defined?(Current) && Current.respond_to?(:user) Current.user elsif user = Thread.current[:current_user] user else raise RuntimeError.new('Current user not found in Policy#current_user') end end