Class: Treaty::Entity::Attribute::Validation::NestedObjectValidator

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

Overview

Validates nested object (hash) attributes against their defined structure.

Purpose

Performs validation for nested object attributes during the validation phase. Ensures hash values conform to the nested attribute definitions.

Responsibilities

  1. Structure Validation - Validates hash structure matches definition
  2. Attribute Validation - Validates each nested attribute's value
  3. Type Safety - Ensures value is a Hash before validation
  4. Validator Caching - Builds and caches validators for performance

Usage

Used for object-type attributes with nested definitions:

object :author do
  string :name, :required
  string :email
  integer :age
end

Validates: { name: "Alice", email: "[email protected]", age: 30 }

Usage in Code

Called by AttributeValidator for nested objects:

validator = NestedObjectValidator.new(attribute)
validator.validate!(hash_value)

Validation Flow

  1. Check if value is a Hash
  2. Build validators for all nested attributes (cached)
  3. For each nested attribute:
    • Extract value from hash
    • Validate using AttributeValidator
  4. Raise exception if any validation fails

Architecture

Uses:

  • AttributeValidator - Validates individual nested attributes
  • Caches validators to avoid rebuilding on each validation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attribute) ⇒ NestedObjectValidator

Creates a new nested object validator

Parameters:

  • attribute (Attribute::Base)

    The object-type attribute with nested attributes



62
63
64
65
# File 'lib/treaty/entity/attribute/validation/nested_object_validator.rb', line 62

def initialize(attribute)
  @attribute = attribute
  @validators_cache = nil
end

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



57
58
59
# File 'lib/treaty/entity/attribute/validation/nested_object_validator.rb', line 57

def attribute
  @attribute
end

Instance Method Details

#validate!(hash) ⇒ void

This method returns an undefined value.

Validates all nested attributes in a hash Skips validation if value is not a Hash

Parameters:

  • hash (Hash)

    The hash to validate

Raises:



73
74
75
76
77
78
79
80
# File 'lib/treaty/entity/attribute/validation/nested_object_validator.rb', line 73

def validate!(hash)
  return unless hash.is_a?(Hash)

  validators.each do |nested_attribute, nested_validator|
    nested_value = hash.fetch(nested_attribute.name, nil)
    nested_validator.validate_value!(nested_value)
  end
end