Class: Pragma::Policy::Base Abstract
- Inherits:
-
Object
- Object
- Pragma::Policy::Base
- Defined in:
- lib/pragma/policy/base.rb
Overview
Subclass and implement action methods to create a policy.
This is the base policy class that all your record-specific policies should inherit from.
A policy provides predicate methods for determining whether a user can perform a specific action on a record.
Direct Known Subclasses
Constant Summary collapse
Instance Attribute Summary collapse
-
#record ⇒ Object
readonly
Returns the value of attribute record.
-
#user ⇒ Object
(also: #context)
readonly
The user operating on the record.
Instance Method Summary collapse
-
#authorize(action) ⇒ Object
Authorizes the user to perform the given action.
-
#initialize(user, record) ⇒ Base
constructor
Initializes the policy.
-
#method_missing(method_name, *args, &block) ⇒ Object
Provides bang form of predicates (
create!
,update!
etc.). -
#respond_to_missing?(method_name, include_private = false) ⇒ Boolean
Returns whether the policy responds to the provided missing method.
Constructor Details
#initialize(user, record) ⇒ Base
Initializes the policy.
26 27 28 29 |
# File 'lib/pragma/policy/base.rb', line 26 def initialize(user, record) @user = user @record = record end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args, &block) ⇒ Object
Provides bang form of predicates (create!
, update!
etc.).
50 51 52 53 |
# File 'lib/pragma/policy/base.rb', line 50 def method_missing(method_name, *args, &block) return super unless method_name[-1] == '!' method_name[0..-2], *args end |
Instance Attribute Details
#record ⇒ Object (readonly)
Returns the value of attribute record.
19 |
# File 'lib/pragma/policy/base.rb', line 19 attr_reader :user, :record |
#user ⇒ Object (readonly) Also known as: context
Returns the user operating on the record.
19 20 21 |
# File 'lib/pragma/policy/base.rb', line 19 def user @user end |
Instance Method Details
#authorize(action) ⇒ Object
Authorizes the user to perform the given action. If not authorized, raises a ForbiddenError.
62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/pragma/policy/base.rb', line 62 def (action) unless respond_to?("#{action}?") fail(ArgumentError, "'#{action}' is not a valid action for this policy.") end return if send("#{action}?") fail( NotAuthorizedError, user: user, action: action, record: record ) end |
#respond_to_missing?(method_name, include_private = false) ⇒ Boolean
Returns whether the policy responds to the provided missing method.
Supports bang forms of predicates (create!
, update!
etc.).
39 40 41 42 |
# File 'lib/pragma/policy/base.rb', line 39 def respond_to_missing?(method_name, include_private = false) return super unless method_name[-1] == '!' respond_to?("#{method_name[0..-2]}?", include_private) || super end |