Class: Stannum::Constraints::Format
- Defined in:
- lib/stannum/constraints/format.rb
Overview
A Format constraint asserts the value is a string matching the given format.
Direct Known Subclasses
Constant Summary collapse
- NEGATED_TYPE =
The :type of the error generated for a matching object.
'stannum.constraints.matches_format'
- TYPE =
The :type of the error generated for a non-matching object.
'stannum.constraints.does_not_match_format'
Instance Attribute Summary collapse
-
#expected_format ⇒ Regex, String
readonly
The expected format.
Attributes inherited from Base
Instance Method Summary collapse
-
#errors_for(actual, errors: nil) ⇒ Stannum::Errors
Generates an errors object for the given object.
-
#initialize(expected_format, **options) ⇒ Format
constructor
A new instance of Format.
-
#matches?(actual) ⇒ true, false
(also: #match?)
Checks that the object is a string with the expected format.
Methods inherited from Base
#==, #clone, #does_not_match?, #dup, #match, #message, #negated_errors_for, #negated_match, #negated_message, #negated_type, #type, #with_options
Constructor Details
#initialize(expected_format, **options) ⇒ Format
Returns a new instance of Format.
33 34 35 36 37 |
# File 'lib/stannum/constraints/format.rb', line 33 def initialize(expected_format, **) @expected_format = expected_format super(expected_format:, **) end |
Instance Attribute Details
#expected_format ⇒ Regex, String (readonly)
Returns the expected format.
40 41 42 |
# File 'lib/stannum/constraints/format.rb', line 40 def expected_format @expected_format end |
Instance Method Details
#errors_for(actual, errors: nil) ⇒ Stannum::Errors
This method should only be called for an object that does not match the constraint. Generating errors for a matching object can result in undefined behavior.
Generates an errors object for the given object.
The errors object represents the difference between the given object and the expected properties or behavior. It may be the same for all objects, or different based on the details of the object or the constraint.
43 44 45 46 47 |
# File 'lib/stannum/constraints/format.rb', line 43 def errors_for(actual, errors: nil) return super if type_constraint.matches?(actual) type_constraint.errors_for(actual, errors:) end |
#matches?(actual) ⇒ true, false Also known as: match?
Checks that the object is a string with the expected format.
55 56 57 58 59 60 61 62 63 |
# File 'lib/stannum/constraints/format.rb', line 55 def matches?(actual) return false unless type_constraint.matches?(actual) if expected_format.is_a?(String) actual.include?(expected_format) else actual.match?(expected_format) end end |