Class: Philiprehberger::TomlKit::Schema

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/toml_kit/schema.rb

Overview

Validates a parsed TOML hash against a schema definition.

Schema format:

{
  "key" => { type: String, required: true },
  "port" => { type: Integer, required: false, default: 8080 },
  "database" => {
    type: Hash,
    properties: {
      "host" => { type: String, required: true },
      "port" => { type: Integer }
    }
  },
  "tags" => { type: Array, items: { type: String } }
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(properties) ⇒ Schema

Build a new schema.

Parameters:

  • properties (Hash)

    schema definition



28
29
30
# File 'lib/philiprehberger/toml_kit/schema.rb', line 28

def initialize(properties)
  @properties = properties
end

Instance Attribute Details

#propertiesObject (readonly)

Returns the value of attribute properties.



23
24
25
# File 'lib/philiprehberger/toml_kit/schema.rb', line 23

def properties
  @properties
end

Instance Method Details

#validate(data) ⇒ Array<String>

Validate a hash against this schema.

Parameters:

  • data (Hash)

    parsed TOML data

Returns:

  • (Array<String>)

    list of validation errors (empty if valid)



36
37
38
39
40
# File 'lib/philiprehberger/toml_kit/schema.rb', line 36

def validate(data)
  errors = []
  validate_properties(data, @properties, [], errors)
  errors
end

#validate!(data) ⇒ true

Validate and raise if invalid.

Parameters:

  • data (Hash)

    parsed TOML data

Returns:

  • (true)

Raises:



47
48
49
50
51
52
# File 'lib/philiprehberger/toml_kit/schema.rb', line 47

def validate!(data)
  errors = validate(data)
  raise SchemaError, "Schema validation failed: #{errors.join('; ')}" unless errors.empty?

  true
end