fhwang.net

validates_with_block

Friday, July 18, 2008

In one of our Rails projects at Diversion Media, our models can get pretty big with validations -- one in particular has almost 20. It ends up being pretty noisy having all those repeated words:
class User < ActiveRecord::Base
  validates_presence_of   :login, :message => 'Please enter a login.'
  validates_uniqueness_of :login, :case_sensitive => false
  validates_format_of     :login, :with => /\A\w*\Z/
  validates_length_of     :login, :within => 4..15
end
So, we wrote validates_with_block, a Rails plugin that allows you to write a more readable set of validations for one model.
class User < ActiveRecord::Base
  validates_login do |login|
    login.present   :message => 'Please enter a login.'
    login.unique    :case_sensitive => false
    login.formatted :with => /\A\w*\Z/
    login.length    :within => 4..15
  end
end
These methods just call the same old validates_* methods; they don't do anything interesting with ActiveRecord beyond that. It's just for keeping things readable, but sometimes readability takes a little extra work.

Tagged: ruby

<< There are worse things than a coup -- right? (Jul 11 2008) | Way down low where the streets are littered (Jul 22 2008) >>