hatch icon indicating copy to clipboard operation
hatch copied to clipboard

Multiple validations per parameter

Open tarolandia opened this issue 11 years ago • 1 comments

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 avatar Mar 20 '14 20:03 tarolandia

@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 :foo is valid or not.
  • The errors array 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?

tonchis avatar Aug 13 '14 14:08 tonchis