tonchis / hatch

An address without a street? A person without a name? You don't need no invalid objects!
MIT License
28 stars 3 forks source link

Multiple validations per parameter #4

Open tarolandia opened 10 years ago

tarolandia commented 10 years ago

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.

tonchis commented 10 years ago

@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

But...

@tarolandia what do you think?