Created
February 11, 2020 13:36
-
-
Save scharrier/a7eb40a8421531bc75d24436cc781244 to your computer and use it in GitHub Desktop.
Dry validation: missing logic example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'dry-validation' | |
Parameter = Dry::Schema.JSON do | |
required(:name).filled(:string) | |
end | |
Reference = Dry::Schema.JSON do | |
required(:$ref).filled(:string) | |
end | |
Operation = Dry::Schema.JSON do | |
required(:parameters).each(:hash, Parameter) | |
# What would be perfect here imo: required(:parameters).each(:hash, Parameter | Reference) | |
# Note: I cannot make `$ref` and `name` optional in a single schema, as we need to verify that it matches one of the other form | |
end | |
class Contract < Dry::Validation::Contract | |
json do | |
required(:paths).each(:hash) do | |
required(:get).hash(Operation) | |
end | |
end | |
end | |
valid_hash = { | |
'paths' => [ | |
{ | |
'get' => { | |
'parameters' => [ | |
{ 'name' => 'hello' }, | |
{ '$ref' => '#/internal/ref' } | |
] | |
} | |
} | |
] | |
} | |
result = Contract.new.call(valid_hash) | |
if result.success? | |
puts "Valid" | |
else | |
puts "Invalid:" | |
result.errors.each { |e| puts "- #{e.path.join('.') + ' ' + e.text}" } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment