Class: Castkit::Validators::BooleanValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/castkit/validators/boolean_validator.rb

Overview

Validator for boolean attributes.

Accepts various representations of boolean values, including strings and integers. Converts common truthy/falsy string values into booleans, otherwise raises a type error.

This validator is typically used internally by ‘Castkit::Types::Boolean`.

Examples:

validator = Castkit::Validators::BooleanValidator.new
validator.call("true", _options: {}, context: :enabled) # => true
validator.call("0", _options: {}, context: :enabled)    # => false
validator.call("nope", _options: {}, context: :enabled) # raises Castkit::AttributeError

Instance Method Summary collapse

Instance Method Details

#call(value, _options:, context:) ⇒ Boolean

Validates the Boolean value.

Parameters:

  • value (Object)

    the input to validate

  • _options (Hash)

    unused, provided for consistency with other validators

  • context (Symbol, String)

    the attribute name or path for error messages

Returns:

  • (Boolean)

Raises:



27
28
29
30
31
32
33
34
35
36
# File 'lib/castkit/validators/boolean_validator.rb', line 27

def call(value, _options:, context:)
  case value.to_s.downcase
  when "true", "1"
    true
  when "false", "0"
    false
  else
    type_error!(:boolean, value, context: context)
  end
end