Forum: Ruby on Rails Problem requiring custom validation

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
6122ae139470e3776aa36316296f87a3?d=identicon&s=25 Cynthia Kiser (Guest)
on 2007-07-10 02:00
(Received via mailing list)
I have occasion to validate email addresses in multiple models over
projects, so I decided to start a custom validation library. Google
led me to this write up that is essentially what I want - but with a
different format -

# lib/custom_validators.rb

module ActiveRecord::Validations::ClassMethods

  def validates_as_email(*attr_names)
    configuration = { :message => "is not a valid email address", :on
=> :save, :allow_nil => true }
    configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)

    validates_each(attr_names,configuration) do |record, attr_name,
      record.errors.add(attr_name, configuration[:message]) unless
value.to_s =~ /(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i


# config/environment.rb

require 'custom_validators'

# app/models/user.rb

class User < ActiveRecord::Base
  validates_as_email        :email

But I had trouble getting my new validation recognized so I could use
it in the same way I use the built in validations. My rails instance
(version 1.2.3) seems to be ignoring my 'require "custom_validators"'
call in environment.rb. The only way I could get around the
NoMethodErrors was to place 'require "custom_validators"' at the top
of the model class where I wanted to use it (e.g. app/models/user.rb).
This isn't killer - but it does mean that I can't seamlessly extend
the Rails core by just hooking things in once.

1. Have things changed since the tutorial I referenced was written? I
found Peter Marklund's article a little less clear to me
(, but it seems to still
imply that placing the custom validations in a file in lib should
cause them to be loaded automatically or perhaps semi-automatically.

2. Is there a way to do what I want? Extend Rails with my custom
validations and only have to hook it in once (not in every model where
I want to use them).

Cynthia Kiser
This topic is locked and can not be replied to.