Sunday, February 11, 2007
Ruby: Validatable
I finished up the 1.1.0 release this morning of Validatable. Validatable is a module that you can mix into your classes to add validations.
Validation of an entire hierarchy of objects with errors aggregated at the root object.
class PersonValidatable currently supports
include Validatable
attr_accessor :name
validates_presence_of :name
end
person = Person.new
person.valid? #=> false
person.errors.on(:name) #=> "can't be empty"
- validates_presence_of
- validates_length_of
- validates_format_of
- validates_confirmation_of
- validates_acceptance_of
Validation of an entire hierarchy of objects with errors aggregated at the root object.
class PersonValidations that turn off after X times of failed attempts.
include Validatable
validates_presence_of :name
attr_accessor :name
end
class PersonPresenter
include Validatable
include_validations_for :person
attr_accessor :person
def initialize(person)
@person = person
end
end
presenter = PersonPresenter.new(Person.new)
presenter.valid? #=> false
presenter.errors.on(:name) #=> "can't be blank"
class PersonValidations can be given levels. If a validation fails on a level the validations for subsequent levels will not be executed.
include Validatable
validates_presence_of :name, :times => 1
attr_accessor :name
end
person = Person.new
person.valid? #=> false
person.valid? #=> true
class PersonSimilar to Rails, Validatable also supports conditional validation.
include Validatable
validates_presence_of :name, :level => 1, :message => "name message"
validates_presence_of :address, :level => 2
attr_accessor :name, :address
end
person = Person.new
person.valid? #=> false
person.errors.on(:name) #=> "name message"
person.errors.on(:address) #=> nil
class Person
include Validatable
attr_accessor :name
validates_format_of :name, :with => /.+/, :if => Proc.new { !name.nil? }
end
Person.new.valid? #=> true
Labels: rails, ruby, validatable, validations




