Skip to content

Instantly share code, notes, and snippets.

@k-hamada
Last active April 10, 2018 10:19
Show Gist options
  • Save k-hamada/87e709761b7dc715ff954abefbd927b4 to your computer and use it in GitHub Desktop.
Save k-hamada/87e709761b7dc715ff954abefbd927b4 to your computer and use it in GitHub Desktop.
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'dry-validation'
end
schema = Dry::Validation.Schema do
optional(:x).filled(:int?)
.when(eql?: 1) { value(:y).filled? > value(:y2).filled? }
.when(eql?: 1) { value(:y2).filled? > value(:y).filled? }
optional(:y).filled(:int?)
optional(:y2).filled(:int?)
optional(:z).filled(:int?)
rule(y_then_x: [:x, :y]) {|x, y| y.filled? > x.filled? }
rule(z_then_x: [:x, :z]) {|x, z| z.filled? > x.filled? }
end
# success
p schema.({})
p schema.(x: 1)
p schema.(x: 1, y: 1, y2: 1)
p schema.(x: 1, z: 1)
p schema.(x: 0)
p schema.(x: 0, y: 1, z: 1)
# failure
p schema.(y: 1)
p schema.(z: 1)
p schema.(x: 1, y: 1)
p schema.(y: 1, z: 1)
p schema.(y: 1, y2: 1)
p schema.(x: 1, z: 1, y2: 1)
@k-hamada
Copy link
Author

#<Dry::Validation::Result output={} errors={}>
#<Dry::Validation::Result output={:x=>1} errors={}>
#<Dry::Validation::Result output={:x=>1, :y=>1, :y2=>1} errors={}>
#<Dry::Validation::Result output={:x=>1, :z=>1} errors={}>
#<Dry::Validation::Result output={:x=>0} errors={}>
#<Dry::Validation::Result output={:x=>0, :y=>1, :z=>1} errors={}>
#<Dry::Validation::Result output={:y=>1} errors={:x_then_y=>["must be filled"]}>
#<Dry::Validation::Result output={:z=>1} errors={:x_then_z=>["must be filled"]}>
#<Dry::Validation::Result output={:x=>1, :y=>1} errors={:y2=>["must be filled"]}>
#<Dry::Validation::Result output={:y=>1, :z=>1} errors={:x_then_y=>["must be filled"], :x_then_z=>["must be filled"]}>
#<Dry::Validation::Result output={:y=>1, :y2=>1} errors={:x_then_y=>["must be filled"]}>
#<Dry::Validation::Result output={:x=>1, :z=>1, :y2=>1} errors={:y=>["must be filled"]}>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment