Skip to content

Instantly share code, notes, and snippets.

@scharrier
Created February 11, 2020 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scharrier/a7eb40a8421531bc75d24436cc781244 to your computer and use it in GitHub Desktop.
Save scharrier/a7eb40a8421531bc75d24436cc781244 to your computer and use it in GitHub Desktop.
Dry validation: missing logic example
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