hatch
hatch copied to clipboard
Multiple validations per parameter
Improve Hatch to allow multiple validations for each parameter/property.
class LoginForm
include Hatch
certify('email', 'must_be_present') do |email|
!email.nil? && !email.empty?
end
certify('email', 'email_must_exist') do |email|
# example using sequel
!User.find(email: email).nil?
end
This feature will allow the developer to use multiple error messages when validating.
@tarolandia You can achieve something similar with the example below.
class Foo
include Hatch
attr :foo
errors = []
certify(:foo, errors) do |foo|
errors.clear
errors << "no foo" if foo.nil?
errors << "foo is bar" if foo == "bar"
errors.empty?
end
not_foo = Foo.hatch
not_foo.errors.on(:foo)
# => ["no foo"]
not_foo = Foo.hatch(foo: "bar")
not_foo.errors.on(:foo)
# => ["foo is bar"]
Foo.hatch(foo: "foo").valid?
# => true
On the plus side this
- Keeps the validation in one place. There's only one block of code deciding if
:foois valid or not. - The
errorsarray could be any object you need, which makes it easy to handle.
But...
- That one block can get messy (that's on the user, though).
- You lose some expressiveness. By reading
certify(:email, :not_empty)I already know what was intended without needing to read the block.
@tarolandia what do you think?