Class: Stannum::Constraint
- Inherits:
-
Stannum::Constraints::Base
- Object
- Stannum::Constraints::Base
- Stannum::Constraint
- Defined in:
- lib/stannum/constraint.rb
Overview
Constraint class for defining a custom or one-off constraint instance.
The Stannum::Constraint class allows you to define a constraint instance with a block, and optionally a type and negated type when generating errors for non-matching objects.
If your use case is more complicated, such as a constraint with multiple expectations and thus different errors depending on the given object, use a subclass of the Stannum::Constraints::Base class instead. For example, an is_odd constraint that checks if an object is an odd integer might have different errors when passed a non-integer object and when passed an even integer, even though both are failing matches.
Likewise, if you want to define a custom constraint class, it is recommended that you use Stannum::Constraints::Base as the base class for all but the simplest constraints.
Constant Summary
Constants inherited from Stannum::Constraints::Base
Stannum::Constraints::Base::NEGATED_TYPE, Stannum::Constraints::Base::TYPE
Instance Attribute Summary
Attributes inherited from Stannum::Constraints::Base
Instance Method Summary collapse
-
#initialize(**options) {|actual| ... } ⇒ Constraint
constructor
A new instance of Constraint.
-
#matches?(actual) ⇒ true, false
(also: #match?)
Checks that the given object matches the constraint.
Methods inherited from Stannum::Constraints::Base
#==, #clone, #does_not_match?, #dup, #errors_for, #match, #message, #negated_errors_for, #negated_match, #negated_message, #negated_type, #type, #with_options
Constructor Details
#initialize(**options) {|actual| ... } ⇒ Constraint
Returns a new instance of Constraint.
53 54 55 56 57 |
# File 'lib/stannum/constraint.rb', line 53 def initialize(**, &block) @definition = block super(**) end |
Instance Method Details
#matches?(actual) ⇒ true, false Also known as: match?
60 61 62 |
# File 'lib/stannum/constraint.rb', line 60 def matches?(actual) @definition ? @definition.call(actual) : super end |