Module: CMDx::Validators::Absence

Extended by:
Absence
Included in:
Absence
Defined in:
lib/cmdx/validators/absence.rb

Overview

Validates that a value is absent or empty

This validator ensures that the given value is nil, empty, or consists only of whitespace. It handles different value types appropriately:

  • Strings: checks for absence of non-whitespace characters

  • Collections: checks for empty collections

  • Other objects: checks for nil values

Instance Method Summary collapse

Instance Method Details

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

Validates that a value is absent or empty

Examples:

Validate string absence

Absence.call("")
# => nil (validation passes)

Validate non-empty string

Absence.call("hello")
# => raises ValidationError

Validate array absence

Absence.call([])
# => nil (validation passes)

Validate non-empty array

Absence.call([1, 2, 3])
# => raises ValidationError

Validate with custom message

Absence.call("hello", message: "Value must be empty")
# => raises ValidationError with custom message

Parameters:

  • value (Object)

    The value to validate for absence

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

    Validation configuration options

Options Hash (options):

  • :message (String)

    Custom error message

Returns:

  • (nil)

    Returns nil if validation passes

Raises:

  • (ValidationError)

    When the value is present, not empty, or contains non-whitespace characters



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cmdx/validators/absence.rb', line 43

def call(value, options = {})
  match =
    if value.is_a?(String)
      /\S/.match?(value)
    elsif value.respond_to?(:empty?)
      !value.empty?
    else
      !value.nil?
    end

  return unless match

  message = options[:message] if options.is_a?(Hash)
  raise ValidationError, message || Locale.t("cmdx.validators.absence")
end