Class: Philiprehberger::SafeYaml::Schema
- Inherits:
-
Object
- Object
- Philiprehberger::SafeYaml::Schema
- Defined in:
- lib/philiprehberger/safe_yaml/schema.rb
Overview
DSL-based schema validation for parsed YAML data.
Instance Method Summary collapse
-
#initialize(&block) ⇒ Schema
constructor
A new instance of Schema.
-
#optional(key, type, rule: nil, message: nil) ⇒ void
Declares an optional key with an expected type.
-
#required(key, type, rule: nil, message: nil) ⇒ void
Declares a required key with an expected type.
-
#validate(data) ⇒ Hash
Validates data against the schema without raising.
-
#validate!(data) ⇒ true
Validates data against the schema, raising on failure.
Constructor Details
#initialize(&block) ⇒ Schema
Returns a new instance of Schema.
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.
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: } end |
#required(key, type, rule: nil, message: nil) ⇒ void
This method returns an undefined value.
Declares a required key with an expected type.
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: } end |
#validate(data) ⇒ Hash
Validates data against the schema without raising.
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.
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 |