Module: CMDx::Validators::Inclusion

Extended by:
Inclusion
Included in:
Inclusion
Defined in:
lib/cmdx/validators/inclusion.rb

Overview

Validates that a value is included in a specified set or range

This validator ensures that the given value is present within a collection of allowed values or falls within a specified range. It supports both discrete value lists and range-based validations.

Instance Method Summary collapse

Instance Method Details

#call(value, options = {}) ⇒ nil

Validates that a value is included in the specified options

Examples:

Include specific values

Inclusion.call("admin", in: ["admin", "user", "guest"])
# => nil (validation passes)

Include values within a range

Inclusion.call(5, in: 1..10)
# => nil (validation passes - 5 is within 1..10)

Include with custom message

Inclusion.call("test", in: ["admin", "user"], message: "must be one of: %{values}")

Parameters:

  • value (Object)

    The value to validate for inclusion

  • options (Hash) (defaults to: {})

    Validation configuration options

Options Hash (options):

  • :in (Array, Range)

    The collection of allowed values or range

  • :within (Array, Range)

    Alias for :in option

  • :message (String)

    Custom error message template

  • :of_message (String)

    Custom message for discrete value inclusions

  • :in_message (String)

    Custom message for range-based inclusions

  • :within_message (String)

    Custom message for range-based inclusions

Returns:

  • (nil)

    Returns nil if validation passes

Raises:

  • (ValidationError)

    When the value is not found in the allowed collection



39
40
41
42
43
44
45
46
47
# File 'lib/cmdx/validators/inclusion.rb', line 39

def call(value, options = {})
  values = options[:in] || options[:within]

  if values.is_a?(Range)
    raise_within_validation_error!(values.begin, values.end, options) unless values.cover?(value)
  elsif Array(values).none? { |v| v === value }
    raise_of_validation_error!(values, options)
  end
end