class Stannum::Constraints::Enum

An enum constraint asserts that the object is one of the given values.

@example Using an Enum Constraint

constraint = Stannum::Constraints::Enum.new('red', 'green', 'blue')

constraint.matches?('red')    #=> true
constraint.matches?('yellow') #=> false

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

matching_values[R]

Public Class Methods

new(first, *rest, **options) click to toggle source

@overload initialize(*expected_values, **options)

@param expected_values [Array] 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/enum.rb, line 26
def initialize(first, *rest, **options)
  expected_values = rest.unshift(first)

  super(expected_values: expected_values, **options)

  @matching_values = Set.new(expected_values)
end

Public Instance Methods

errors_for(actual, errors: nil) click to toggle source

(see Stannum::Constraints::Base#errors_for)

# File lib/stannum/constraints/enum.rb, line 35
def errors_for(actual, errors: nil) # rubocop:disable Lint/UnusedMethodArgument
  (errors || Stannum::Errors.new).add(type, values: expected_values)
end
expected_values() click to toggle source

@return [Array] the possible values for the object.

# File lib/stannum/constraints/enum.rb, line 40
def expected_values
  options[:expected_values]
end
match?(actual)
Alias for: matches?
matches?(actual) click to toggle source

Checks that the object is in the list of expected values.

@return [true, false] false if the object is in the list of expected

values, otherwise true.

@see Stannum::Constraint#matches?

# File lib/stannum/constraints/enum.rb, line 55
def matches?(actual)
  @matching_values.include?(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/enum.rb, line 45
def negated_errors_for(actual, errors: nil) # rubocop:disable Lint/UnusedMethodArgument
  (errors || Stannum::Errors.new).add(negated_type, values: expected_values)
end