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
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
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.
blog comments powered by Disqus
Tagged: ruby

« Previous post

Next post »