Last active
May 11, 2016 19:06
-
-
Save AMHOL/bbfa774b51203cf0a59601a34e7fb05c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: '[email protected]') | |
user_validator.call( | |
name: 'John', | |
email: '[email protected]' | |
) | |
# Failure | |
user_validator.call( | |
name: 'Jill', | |
email: '[email protected]' | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment