Skip to content

Instantly share code, notes, and snippets.

@solnic
Last active June 1, 2016 22:10
Show Gist options
  • Save solnic/6030ad52c7600257ed09d13537f4f498 to your computer and use it in GitHub Desktop.
Save solnic/6030ad52c7600257ed09d13537f4f498 to your computer and use it in GitHub Desktop.
require 'dry-validation'
SCHEMA = Dry::Validation.Schema do
configure do
config.input_processor = :sanitizer
def self.messages
Dry::Validation::Messages.default.merge(en: { errors: { unique?: "oops not unique" }})
end
def unique?(value)
value.flat_map { |kp| kp[:key_phrase] }.uniq.size == value.size
end
end
required(:key_phrases).each do
schema do
required(:weight).filled(gteq?: 0, lteq?: 4)
required(:key_phrase).filled
end
end
rule(unique_phrases: [:key_phrases]) do |key_phrases|
key_phrases.unique?
end
end
module JsonPayload
def self.example_repeated_keys
{
name: "name",
user_id: "01dd7006-8b96-48e8-954e-5a9da4cd72e0",
bap_control_id: "01dd7006-8b96-48e8-954e-5a9da4cd72e0",
implementation: "imp lang",
key_phrases: [
{
key_phrase: "ph1",
weight: 5.3
},
{
key_phrase: "ph1",
weight: 6.2
}
]
}
end
def self.example_normal
{
name: "name",
user_id: "01dd7006-8b96-48e8-954e-5a9da4cd72e0",
bap_control_id: "01dd7006-8b96-48e8-954e-5a9da4cd72e0",
implementation: "imp lang",
key_phrases: [
{
key_phrase: "ph1",
weight: 5.3
},
{
key_phrase: "ph2",
weight: 6.2
}
]
}
end
end
puts SCHEMA.(JsonPayload.example_normal).messages.inspect
puts SCHEMA.(JsonPayload.example_repeated_keys).messages.inspect
@eduardodeoh
Copy link

eduardodeoh commented May 30, 2016

hi @solnic, so this validation, don't works: required(:weight).filled(gteq?: 0, lteq?: 4). Only key_phrases rule works. I though to make this validations in steps, like: validates key_phrases rule and if true validates weight value between 0 and 4. For now, only key_phrases rule validation is ok.

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