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.
323 324 325 326 |
# File 'lib/coradoc/validation.rb', line 323 def initialize @fields = {} @rules = [] end |
Instance Attribute Details
#fields ⇒ Object (readonly)
Returns the value of attribute fields.
311 312 313 |
# File 'lib/coradoc/validation.rb', line 311 def fields @fields end |
#rules ⇒ Object (readonly)
Returns the value of attribute rules.
311 312 313 |
# File 'lib/coradoc/validation.rb', line 311 def rules @rules end |
Class Method Details
.define { ... } ⇒ Schema
Define a new schema
317 318 319 320 321 |
# File 'lib/coradoc/validation.rb', line 317 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
361 362 363 |
# File 'lib/coradoc/validation.rb', line 361 def add_rule(rule) @rules << rule end |
#optional(name, type: nil, **options) ⇒ void
This method returns an undefined value.
Define an optional field
344 345 346 |
# File 'lib/coradoc/validation.rb', line 344 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
334 335 336 |
# File 'lib/coradoc/validation.rb', line 334 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
353 354 355 |
# File 'lib/coradoc/validation.rb', line 353 def rule(name, &block) @rules << Rules::Custom.new(name, block: block) end |
#validate(document) ⇒ Result
Validate a document
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
# File 'lib/coradoc/validation.rb', line 369 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 |