Class: EasyTalk::ValidationAdapters::ActiveModelAdapter

Inherits:
Base
  • Object
show all
Defined in:
lib/easy_talk/validation_adapters/active_model_adapter.rb

Overview

ActiveModel validation adapter.

This is the default adapter that converts JSON Schema constraints into ActiveModel validations. It provides the same validation behavior as the original EasyTalk::ValidationBuilder.

Examples:

Using the ActiveModel adapter (default)

class User
  include EasyTalk::Model

  define_schema do
    property :email, String, format: 'email'
  end
end

user = User.new(email: 'invalid')
user.valid? # => false
user.errors[:email] # => ["must be a valid email address"]

Instance Method Summary collapse

Constructor Details

This class inherits a constructor from EasyTalk::ValidationAdapters::Base

Instance Method Details

#apply_validations

This method returns an undefined value.

Apply validations based on property type and constraints.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/easy_talk/validation_adapters/active_model_adapter.rb', line 30

def apply_validations
  # Determine if the type is boolean
  type_class = get_type_class(@type)
  is_boolean = type_class == [TrueClass, FalseClass] ||
               type_class == TrueClass ||
               type_class == FalseClass ||
               TypeIntrospection.boolean_type?(@type)

  # Determine if the type is an array (empty arrays should be valid)
  is_array = type_class == Array || @type.is_a?(T::Types::TypedArray)

  # Skip presence validation for booleans, nilable types, and arrays
  # (empty arrays are valid - use min_items constraint if you need non-empty)
  apply_presence_validation unless optional? || is_boolean || nilable_type? || is_array

  if nilable_type?
    # For nilable types, get the inner type and apply validations to it
    inner_type = extract_inner_type(@type)
    apply_type_validations(inner_type)
  else
    apply_type_validations(@type)
  end

  # Common validations for most types
  apply_enum_validation if @constraints[:enum]
  apply_const_validation if @constraints[:const]
end