Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'dry-validation'
User = Struct.new(:name, :email)
class UserRepository
USERS = []
def create(attributes)
USERS << User.new(*attributes.values_at(:name, :email))
end
def find_by_email(email)
USERS.find { |user| user.email == email }
end
end
UserSchema = Dry::Validation.JSON do
configure do
option :uniqueness_finder
def self.messages
super.merge(en: { errors: { unique?: 'must be unique' } })
end
def unique?(value)
uniqueness_finder.call(value).nil?
end
end
required(:name).required
required(:email).filled(:unique?)
end
user_repo = UserRepository.new
user_validator = UserSchema.with(uniqueness_finder: user_repo.method(:find_by_email))
user_repo.create(name: 'John', email: 'john@dry-rb.org')
user_validator.call(
name: 'John',
email: 'john@dry-rb.org'
)
# Failure
user_validator.call(
name: 'Jill',
email: 'jill@dry-rb.org'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.