Ruby on Rails is radically changing the way developers look at Web
applications, and it’s great to see all the excitement that surrounds the many
innovative features it offers. One of these features is in-model
validation, which is understandably seen as an improvement over validation tied
to the presentation framework.
In
this entry, Todd Huss shows a convincing example of this approach:
class Entry < ActiveRecord::Base
# Relationships
belongs_to :bliki# Validation
validates_length_of :name, :within => 6..100
validates_uniqueness_of :name
validates_format_of :name, :with => /^\w+$/,
:message => "cannot contain whitespace"
validates_length_of :content, :minimum => 10
validates_associated :bliki
end
This kind of code is fairly usual to any regular Ruby on Rails developer to
the point where it’s actually easy to overlook that there is something very
wrong with it: there is no easy way to capture this validation logic for
reuse elsewhere.
I could move this validation to a common class but it’s not good enough, for
two reasons:
I still might want to fine tune a few parameters here and there (sometimes,
the length of the name can be 6..100, other times 5..10 but the other
constraints need to stay in place).
Not all my ActiveRecord objects extend the same class.
Has anyone tried to use a mix-in to achieve this? Any other idea?