Skip to content

Instantly share code, notes, and snippets.

@mguentner
Last active August 20, 2018 10:40
Show Gist options
  • Save mguentner/28a48786af18e5d0ba869664d5ed8c3a to your computer and use it in GitHub Desktop.
Save mguentner/28a48786af18e5d0ba869664d5ed8c3a to your computer and use it in GitHub Desktop.
#!/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