Module: Yaml::Converter::Validation

Defined in:
lib/yaml/converter/validation.rb

Overview

YAML validation helpers.

This module provides simple validation by attempting to parse input using
Psych.safe_load with a minimal, safe set of options. It does not raise on
failure; instead it returns a structured Hash indicating status and error.

Class Method Summary collapse

Class Method Details

.validate_file(path) ⇒ Hash

Validate a YAML file by reading it and delegating to validate_string.

Examples:

Yaml::Converter::Validation.validate_file("config.yml")
#=> { status: :ok, error: nil }

Parameters:

  • path (String)

    filesystem path to a YAML file

Returns:



58
59
60
61
# File 'lib/yaml/converter/validation.rb', line 58

def validate_file(path)
  content = File.read(path)
  validate_string(content)
end

.validate_string(yaml_string) ⇒ Hash

Validate a YAML string by attempting to load it safely via Psych.

Uses Psych.safe_load with:

  • permitted_classes: []
  • permitted_symbols: []
  • aliases: true

]

Examples:

Success

Yaml::Converter::Validation.validate_string("foo: bar")
#=> { status: :ok, error: nil }

Failure

Yaml::Converter::Validation.validate_string(": : :")
#=> { status: :fail, error: #<Psych::SyntaxError ...> }

Parameters:

  • yaml_string (String)

    the YAML content to validate

Returns:

  • (Hash)

    a result hash

  • (Hash)

    [
    { status: :ok, error: nil } when parsing succeeds,
    { status: :fail, error: Exception } when parsing fails



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/yaml/converter/validation.rb', line 37

def validate_string(yaml_string)
  # Psych.safe_load requires permitted classes for complex YAML; for our purposes,
  # allow basic types and symbols off.
  Psych.safe_load(
    yaml_string,
    permitted_classes: [],
    permitted_symbols: [],
    aliases: true,
  )
  {status: :ok, error: nil}
rescue StandardError => e
  {status: :fail, error: e}
end