Last active
August 20, 2018 10:40
-
-
Save mguentner/28a48786af18e5d0ba869664d5ed8c3a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'byebug' | |
require 'dry-validation' | |
module MyPredicates | |
include Dry::Logic::Predicates | |
predicate(:nested_one?) do |value| | |
(value.is_a? Hash) && value.key?(:alpha) | |
end | |
predicate(:nested_two?) do |value| | |
(value.is_a? Hash) && value.key?(:charlie) | |
end | |
predicate(:nested_three?) do |value| | |
(value.is_a? Hash) && value.key?(:echo) | |
end | |
end | |
NestedSchemaOne = Dry::Validation.Schema do | |
required(:alpha).filled | |
required(:bravo).filled | |
end | |
NestedSchemaTwo = Dry::Validation.Schema do | |
required(:charlie).filled | |
required(:delta).filled | |
end | |
NestedSchemaThree = Dry::Validation.Schema do | |
required(:echo).filled | |
required(:foxtrot).filled | |
end | |
ParentSchema = Dry::Validation.Schema do | |
configure do | |
predicates(MyPredicates) | |
end | |
required(:foo).filled | |
required(:nested) do | |
nested_one?.then(schema(NestedSchemaOne)).and(nested_two?.then(schema(NestedSchemaTwo))).and(nested_three?.then(schema(NestedSchemaThree))) | |
end | |
end | |
print(ParentSchema.( | |
foo: 'bar', | |
nested: { alpha: '123' } | |
).messages) | |
print(ParentSchema.( | |
foo: 'bar2', | |
nested: { charlie: '123' } | |
).messages) | |
print(ParentSchema.( | |
foo: 'bar2', | |
nested: { charlie: '123', delta: 'force' } | |
).messages) | |
print(ParentSchema.( | |
foo: 'bar2', | |
nested: { echo: 'hello world' } | |
).messages) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment