Skip to content

Instantly share code, notes, and snippets.

@AMHOL
Last active May 11, 2016 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AMHOL/bbfa774b51203cf0a59601a34e7fb05c to your computer and use it in GitHub Desktop.
Save AMHOL/bbfa774b51203cf0a59601a34e7fb05c to your computer and use it in GitHub Desktop.
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