Module: CMDx::Validators::Presence

Extended by:
Presence
Included in:
Presence
Defined in:
lib/cmdx/validators/presence.rb

Overview

Validates that a value is present and not empty

This validator ensures that the given value exists and contains meaningful content. It handles different value types appropriately:

  • Strings: checks for non-whitespace characters

  • Collections: checks for non-empty collections

  • Other objects: checks for non-nil values

Instance Method Summary collapse

Instance Method Details

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

Validates that a value is present and not empty

Examples:

Validate string presence

Presence.call("hello world")
# => nil (validation passes)

Validate empty string

Presence.call("   ")
# => raises ValidationError

Validate array presence

Presence.call([1, 2, 3])
# => nil (validation passes)

Validate empty array

Presence.call([])
# => raises ValidationError

Validate with custom message

Presence.call(nil, message: "Value cannot be blank")
# => raises ValidationError with custom message

Parameters:

  • value (Object)

    The value to validate for presence

  • 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 empty, nil, or contains only whitespace



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cmdx/validators/presence.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 if match

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