Class: Treaty::Attribute::Validation::NestedArrayValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/treaty/attribute/validation/nested_array_validator.rb

Overview

Validates array elements against nested attribute definitions.

## Purpose

Performs validation for nested array attributes during the validation phase. Handles both simple arrays (with :_self attribute) and complex arrays (objects).

## Responsibilities

  1. **Simple Array Validation** - Validates primitive values in arrays

  2. **Complex Array Validation** - Validates hash objects within arrays

  3. **Error Context** - Provides clear error messages with array index

  4. **Type Checking** - Ensures elements match expected types

## Array Types

### Simple Array (‘:_self` attribute) Array containing primitive values (strings, integers, etc.)

“‘ruby array :tags do

string :_self  # Array of strings

end “‘

Validates: ‘[“ruby”, “rails”, “api”]`

### Complex Array (regular attributes) Array containing hash objects with defined structure

“‘ruby array :authors do

string :name, :required
string :email

end “‘

Validates: ‘[{ name: “Alice”, email: “[email protected]” }, …]`

## Usage

Called by AttributeValidator for nested arrays:

validator = NestedArrayValidator.new(attribute)
validator.validate!(array_value)

## Error Handling

Provides contextual error messages including:

  • Array attribute name

  • Element index (0-based)

  • Specific validation error

Example error:

"Error in array 'tags' at index 2: Element must match one of the defined types"

## Architecture

Uses:

  • ‘AttributeValidator` - Validates individual elements

  • Caches validators for performance

  • Separates self validators from regular validators

Instance Method Summary collapse

Constructor Details

#initialize(attribute) ⇒ NestedArrayValidator

Creates a new nested array validator

Parameters:

  • attribute (Attribute::Base)

    The array-type attribute with nested attributes



72
73
74
75
76
# File 'lib/treaty/attribute/validation/nested_array_validator.rb', line 72

def initialize(attribute)
  @attribute = attribute
  @self_validators = nil
  @regular_validators = nil
end

Instance Method Details

#validate!(array) ⇒ void

This method returns an undefined value.

Validates all items in an array Skips validation if value is not an Array

Parameters:

  • array (Array)

    The array to validate

Raises:



84
85
86
87
88
89
90
91
92
# File 'lib/treaty/attribute/validation/nested_array_validator.rb', line 84

def validate!(array)
  return unless array.is_a?(Array)

  array.each_with_index do |array_item, index|
    validate_self_array_item!(array_item, index) if self_validators.any?

    validate_regular_array_item!(array_item, index) if regular_validators.any?
  end
end