Class: Philiprehberger::SafeYaml::Schema

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

Overview

DSL-based schema validation for parsed YAML data.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Schema

Returns a new instance of Schema.

Parameters:

  • block (Proc)

    DSL block defining required and optional fields



8
9
10
11
# File 'lib/philiprehberger/safe_yaml/schema.rb', line 8

def initialize(&block)
  @fields = []
  instance_eval(&block) if block
end

Instance Method Details

#optional(key, type, rule: nil, message: nil) ⇒ void

This method returns an undefined value.

Declares an optional key with an expected type.

Parameters:

  • key (String, Symbol)

    the key that may be present

  • type (Class)

    the expected type if the key is present

  • rule (Proc, nil) (defaults to: nil)

    optional validation predicate receiving the value

  • message (String, nil) (defaults to: nil)

    custom error message when rule fails



31
32
33
# File 'lib/philiprehberger/safe_yaml/schema.rb', line 31

def optional(key, type, rule: nil, message: nil)
  @fields << { key: key.to_s, type: type, required: false, rule: rule, message: message }
end

#required(key, type, rule: nil, message: nil) ⇒ void

This method returns an undefined value.

Declares a required key with an expected type.

Parameters:

  • key (String, Symbol)

    the key that must be present

  • type (Class)

    the expected type of the value

  • rule (Proc, nil) (defaults to: nil)

    optional validation predicate receiving the value

  • message (String, nil) (defaults to: nil)

    custom error message when rule fails



20
21
22
# File 'lib/philiprehberger/safe_yaml/schema.rb', line 20

def required(key, type, rule: nil, message: nil)
  @fields << { key: key.to_s, type: type, required: true, rule: rule, message: message }
end

#validate(data) ⇒ Hash

Validates data against the schema without raising.

Parameters:

  • data (Hash)

    the parsed YAML data to validate

Returns:

  • (Hash)

    result with :valid (Boolean) and :errors (Array<String>)



51
52
53
54
# File 'lib/philiprehberger/safe_yaml/schema.rb', line 51

def validate(data)
  errors = collect_errors(data)
  { valid: errors.empty?, errors: errors }
end

#validate!(data) ⇒ true

Validates data against the schema, raising on failure.

Parameters:

  • data (Hash)

    the parsed YAML data to validate

Returns:

  • (true)

    if validation passes

Raises:



40
41
42
43
44
45
# File 'lib/philiprehberger/safe_yaml/schema.rb', line 40

def validate!(data)
  result = validate(data)
  return true if result[:valid]

  raise SchemaError, result[:errors].join('; ')
end