Forum: Ruby on Rails DRY validation

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ea627ef000ec92c6cdd5a4c14075e740?d=identicon&s=25 Dan Kubb (Guest)
on 2006-04-27 23:29
(Received via mailing list)
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi all,

A few months ago someone posted a message about specifying validates_*
constraints on a per-attribute basis.  I just created a small plugin
that
allows you to do this.

Here's an example from one of my models:

   class Country < ActiveRecord::Base
     attribute :name, :string do |a|
       a.validates_length :within => 1..48
       a.validates_format :with => /\A[A-Z](?:\s*['\(-]?[A-Za-z]+[,\.
\)]?)*\z/
       a.validates_uniqueness
     end

     attribute :code_alpha2, :string do |a|
       a.validates_length :is => 2
       a.validates_format :with => /\A[A-Z]+\z/
       a.validates_uniqueness
     end

     attribute :code_alpha3, :string do |a|
       a.validates_length :is => 3
       a.validates_format :with => /\A[A-Z]+\z/
       a.validates_uniqueness
     end

     attribute :phone_code, :integer, :allow_nil => true do |a|
       a.validates_numericality :greater_than_or_equal_to =>
1, :less_than_or_equal_to => 9999
     end
   end

The advantage of this it DRYs up the validation rules since you
don't have to specify the name of the attribute over and over.
Plus it automatically sets validates_presence_of for the attribute
unless you set allow_nil as true -- as shown in the phone_code
attribute above.

The plugin can be downloaded from here:

   http://onautopilot.com/oss/rails/active_attribute.tgz

One nice extra benefit is when I rearranged my validation rules
on a per-attribute basis I found a few attributes I forgot
to validate.  I used the annotate_models plug to add a list of
every column to the top of my model, and proceeded to add
validation rules for each of the forgotten attributes.  It
turned out to be a nice way to make sure the bases were better
covered.

So anyway, give it a shot and let me know how it works
out for you.

- --

Thanks,

Dan
__________________________________________________________________

Dan Kubb
Autopilot Marketing Inc.

Email: dan.kubb@autopilotmarketing.com
Phone: 1 (604) 820-0212
Web:   http://autopilotmarketing.com/
vCard: http://autopilotmarketing.com/~dan.kubb/vcard
__________________________________________________________________



-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (Darwin)

iD8DBQFEUTdI4DfZD7OEWk0RAlCAAJ0Zk8FVJ6hlf0IbvvPEsLmGcElK4QCfbMt4
9pVmbpKD4IZfnazQwo9fWdk=
=SeQ3
-----END PGP SIGNATURE-----
This topic is locked and can not be replied to.