This post originated from an RSS feed registered with Ruby Buzz
by Francis Hwang.
Original Post: validates_with_block
Feed Title: Francis Hwang's site: ruby
Feed URL: http://fhwang.net/syndicate/ruby.atom
Feed Description: Author & artist Francis Hwang's personal site.
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.