Skip to content

Instantly share code, notes, and snippets.

@timriley
Created January 10, 2017 02:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timriley/3fe04be6cffc0f39ef402b3c6f5547a4 to your computer and use it in GitHub Desktop.
Save timriley/3fe04be6cffc0f39ef402b3c6f5547a4 to your computer and use it in GitHub Desktop.
Example of dry-validation predicate for "unique within some scope"
UserSchema = Dry::Validation.Schema do
configure do
# Hard-coding the custom error messages
def self.messages
Dry::Validation::Messages.default.merge(
en: {errors: {unique_within_account?: 'is not unique within this account'}}
)
end
# Here's the custom predicate
def unique_within_account?(account_id, user_name)
# Faking this out here. IRL you'd use an injected option or a hard-coded
# lookup to some account/user data.
!user_name.include?(account_id.to_s)
end
end
required(:account_id).filled(:int?)
required(:name).filled
rule(name: [:account_id, :name]) do |account_id, name|
name.unique_within_account?(account_id)
end
end
valid_input = {account_id: 1, name: "my_name"}
# UserSchema.(valid_input)
# => #<Dry::Validation::Result output={:account_id=>1, :name=>"my_name"} errors={}>
invalid_input = {account_id: 99, name: "my_name_99"}
UserSchema.(invalid_input)
# => #<Dry::Validation::Result output={:account_id=>99, :name=>"my_name_99"} errors={:name=>["is not unique within this account"]}>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment