Skip to content

Instantly share code, notes, and snippets.

@k-hamada
Created April 16, 2018 06:20
Show Gist options
  • Save k-hamada/7227b1939fe9b6514f705a2ca6b168e4 to your computer and use it in GitHub Desktop.
Save k-hamada/7227b1939fe9b6514f705a2ca6b168e4 to your computer and use it in GitHub Desktop.
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'dry-validation'
end
module Predicates
include Dry::Logic::Predicates
predicate(:shift?) do |value|
%w(Up Down UpRate DownRate).include? value
end
predicate(:up?) do |value|
%w(Up UpRate).include? value
end
predicate(:down?) do |value|
%w(Down DownRate).include? value
end
predicate(:rate?) do |value|
%w(UpRate DownRate).include? value
end
end
schema = Dry::Validation.Schema do
configure do
predicates(Predicates)
def self.messages
super.merge(
en: { errors: {
shift?: '%{value} not shift',
up?: '%{value} not up',
down?: '%{value} not down',
rate?: '%{value} not rate',
} }
)
end
end
optional(:y).filled(:shift?)
optional(:x).filled(:int?)
.when(included_in?: [1, 3]) {
required(:y).filled(:up?)
}
.when(included_in?: [2, 4]) {
required(:y).filled(:down?)
}
.when(included_in?: [3, 4]) {
required(:y).filled(:rate?)
}
end
(1..4).each do |i|
p schema.({x: i, y: "A"})
p schema.({x: i, y: "Up"})
p schema.({x: i, y: "Down"})
p schema.({x: i, y: "UpRate"})
p schema.({x: i, y: "DownRate"})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment