In a model I have following validates_format_of. Is there an easy way to
DRY this up? It seems to be rather repetitive.
validates_format_of :expiration_date, :with =>
/^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
validates_format_of :activation_date, :with =>
/^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
validates_format_of :some_other_date, :with =>
/^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
…
Thanks
Hi Jens,
validates_format_of takes a regular expression as its argument:
with - The regular expression used to validate the format with (note: must be supplied!)
… so you just assign the regular expression to a variable
date_format = /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
… and use it in your validates_format_of calls as follows:
validates_format_of :expiration_date, :with => date_format
validates_format_of :activation_date, :with => date_format
validates_format_of :some_other_date, :with => date_format
Here’s how that works:
~ $ irb
date_format = /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
=> /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
date_format.class
=> Regexp
/^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/.class
=> Regexp
exit
~ $ _
Peter
Sigh! … so easy!
Thanks Peter for your time
Hi Jens,
validates_format_of takes a regular expression as its argument:
• with - The regular expression used to validate the format with
(note: must be supplied!)
… so you just assign the regular expression to a variable
date_format = /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
… and use it in your validates_format_of calls as follows:
validates_format_of :expiration_date, :with => date_format
validates_format_of :activation_date, :with => date_format
validates_format_of :some_other_date, :with => date_format
Note that class of the regexp:
~ $ irb
date_format = /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
=> /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
date_format.class
=> Regexp
/^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/.class
=> Regexp
exit
~ $
DRY is the future 
Peter
On Jun 7, 2008, at 7:59 AM, Jens – wrote:
/^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/
…
I wrote a series of custom validations that in addition to defining a
number of common character patterns as named validations, it also
allowed multiple fields per validation
http://www.railsdev.ws/blog/11/custom-validations-in-rails/
It made a huge difference in DRYness and the amount of code needed
for validations.
–
def gw
writes_at ‘www.railsdev.ws’
end