Class: Coradoc::Validation::Schema
- Inherits:
-
Object
- Object
- Coradoc::Validation::Schema
- Defined in:
- lib/coradoc/validation.rb
Overview
Validation schema definition
Instance Attribute Summary collapse
-
#fields ⇒ Object
readonly
Returns the value of attribute fields.
-
#rules ⇒ Object
readonly
Returns the value of attribute rules.
Class Method Summary collapse
-
.define { ... } ⇒ Schema
Define a new schema.
Instance Method Summary collapse
-
#add_rule(rule) ⇒ void
Add a pre-built rule.
-
#initialize ⇒ Schema
constructor
A new instance of Schema.
-
#optional(name, type: nil, **options) ⇒ void
Define an optional field.
-
#required(name, type: nil, **options) ⇒ void
Define a required field.
-
#rule(name) { ... } ⇒ void
Add a custom validation rule.
-
#validate(document) ⇒ Result
Validate a document.
Constructor Details
#initialize ⇒ Schema
Returns a new instance of Schema.
314 315 316 317 |
# File 'lib/coradoc/validation.rb', line 314 def initialize @fields = {} @rules = [] end |
Instance Attribute Details
#fields ⇒ Object (readonly)
Returns the value of attribute fields.
302 303 304 |
# File 'lib/coradoc/validation.rb', line 302 def fields @fields end |
#rules ⇒ Object (readonly)
Returns the value of attribute rules.
302 303 304 |
# File 'lib/coradoc/validation.rb', line 302 def rules @rules end |
Class Method Details
.define { ... } ⇒ Schema
Define a new schema
308 309 310 311 312 |
# File 'lib/coradoc/validation.rb', line 308 def self.define(&block) schema = new schema.instance_eval(&block) if block schema end |
Instance Method Details
#add_rule(rule) ⇒ void
This method returns an undefined value.
Add a pre-built rule
352 353 354 |
# File 'lib/coradoc/validation.rb', line 352 def add_rule(rule) @rules << rule end |
#optional(name, type: nil, **options) ⇒ void
This method returns an undefined value.
Define an optional field
335 336 337 |
# File 'lib/coradoc/validation.rb', line 335 def optional(name, type: nil, **) @fields[name] = { required: false, type: type, ** } end |
#required(name, type: nil, **options) ⇒ void
This method returns an undefined value.
Define a required field
325 326 327 |
# File 'lib/coradoc/validation.rb', line 325 def required(name, type: nil, **) @fields[name] = { required: true, type: type, ** } end |
#rule(name) { ... } ⇒ void
This method returns an undefined value.
Add a custom validation rule
344 345 346 |
# File 'lib/coradoc/validation.rb', line 344 def rule(name, &block) @rules << Rules::Custom.new(name, block: block) end |
#validate(document) ⇒ Result
Validate a document
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
# File 'lib/coradoc/validation.rb', line 360 def validate(document) result = Result.new # Validate fields @fields.each do |name, config| validate_field(document, name, config, result) end # Run custom rules @rules.each do |rule| errors = rule.validate(document, schema: self) errors.each { |e| result.add_error(e, code: rule.name) } end result end |