class Stannum::Constraints::Union
Asserts that the object matches one of the given constraints.
@example Using a Union
Constraint
.
false_constraint = Stannum::Constraint.new { |actual| actual == false } true_constraint = Stannum::Constraint.new { |actual| actual == true } union_constraint = Stannum::Constraints::Union.new( false_constraint, true_constraint ) constraint.matches?(nil) #=> false constraint.matches?(false) #=> true constraint.matches?(true) #=> true
Constants
- NEGATED_TYPE
The :type of the error generated for a matching object.
- TYPE
The :type of the error generated for a non-matching object.
Attributes
expected_constraints[R]
@return [Array<Stannum::Constraints::Base>] the possible values for the
object.
Public Class Methods
new(first, *rest, **options)
click to toggle source
@overload initialize(*expected_constraints, **options)
@param expected_constraints [Array<Stannum::Constraints::Base>] The possible values for the object. @param options [Hash<Symbol, Object>] Configuration options for the constraint. Defaults to an empty Hash.
Calls superclass method
Stannum::Constraints::Base::new
# File lib/stannum/constraints/union.rb, line 31 def initialize(first, *rest, **options) expected_constraints = rest.unshift(first) super(expected_constraints: expected_constraints, **options) @expected_constraints = expected_constraints end
Public Instance Methods
errors_for(actual, errors: nil)
click to toggle source
(see Stannum::Constraints::Base#errors_for
)
# File lib/stannum/constraints/union.rb, line 44 def errors_for(actual, errors: nil) # rubocop:disable Lint/UnusedMethodArgument (errors || Stannum::Errors.new).add(type, constraints: expected_values) end
matches?(actual)
click to toggle source
Checks that the object matches at least one of the given constraints.
@return [true, false] false if the object matches a constraint, otherwise
false.
@see Stannum::Constraint#matches?
# File lib/stannum/constraints/union.rb, line 54 def matches?(actual) expected_constraints.any? { |constraint| constraint.matches?(actual) } end
Also aliased as: match?
negated_errors_for(actual, errors: nil)
click to toggle source
(see Stannum::Constraints::Base#negated_errors_for
)
# File lib/stannum/constraints/union.rb, line 60 def negated_errors_for(actual, errors: nil) # rubocop:disable Lint/UnusedMethodArgument (errors || Stannum::Errors.new) .add(negated_type, constraints: negated_values) end
Private Instance Methods
expected_values()
click to toggle source
# File lib/stannum/constraints/union.rb, line 67 def expected_values @expected_constraints.map do |constraint| { options: constraint.options, type: constraint.type } end end
negated_values()
click to toggle source
# File lib/stannum/constraints/union.rb, line 76 def negated_values @expected_constraints.map do |constraint| { negated_type: constraint.negated_type, options: constraint.options } end end