Class: Policy
- Defined in:
- lib/clean-policy/base.rb,
lib/clean-policy/error.rb,
lib/clean-policy/proxy.rb
Overview
true / false @model.can.write?
raise error or return true @model.can.write!
redirect on error or return true @model.can.write! { redirect_to ‘/login’ }
Defined Under Namespace
Instance Attribute Summary collapse
-
#action ⇒ Object
readonly
Returns the value of attribute action.
-
#model ⇒ Object
readonly
Returns the value of attribute model.
-
#user ⇒ Object
readonly
Returns the value of attribute user.
Instance Method Summary collapse
- #before(action) ⇒ Object
-
#call(*args, &block) ⇒ Object
call has to be isolated because specific of error handling.
- #can ⇒ Object
-
#can?(action, *args, &block) ⇒ Boolean
pass block if you want to handle errors yourself return true if false if block is passed.
- #error(message) ⇒ Object
-
#initialize(model:, user:) ⇒ Policy
constructor
A new instance of Policy.
Constructor Details
#initialize(model:, user:) ⇒ Policy
Returns a new instance of Policy.
12 13 14 15 |
# File 'lib/clean-policy/base.rb', line 12 def initialize model:, user: @model = model @user = user end |
Instance Attribute Details
#action ⇒ Object (readonly)
Returns the value of attribute action.
10 11 12 |
# File 'lib/clean-policy/base.rb', line 10 def action @action end |
#model ⇒ Object (readonly)
Returns the value of attribute model.
10 11 12 |
# File 'lib/clean-policy/base.rb', line 10 def model @model end |
#user ⇒ Object (readonly)
Returns the value of attribute user.
10 11 12 |
# File 'lib/clean-policy/base.rb', line 10 def user @user end |
Instance Method Details
#before(action) ⇒ Object
58 59 60 |
# File 'lib/clean-policy/base.rb', line 58 def before action false end |
#call(*args, &block) ⇒ Object
call has to be isolated because specific of error handling
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/clean-policy/base.rb', line 34 def call *args, &block raise Error.new 'User is not defined' unless @user return true if before(@action) return true if send(@action, *args) raise Error.new('Access disabled in policy') rescue Policy::Error => e error = e. error += " - #{self.class}.#{@action}" if defined?(Lux) && Lux.config(:dump_errors) if block block.call(error) false else raise Policy::Error, error end end |
#can?(action, *args, &block) ⇒ Boolean
pass block if you want to handle errors yourself return true if false if block is passed
19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/clean-policy/base.rb', line 19 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 |