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 - http://www.yoman.com.sg/ruby-and-rails
# 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, value|
      record.errors.add(attr_name, configuration[:message]) unless
value.to_s =~ /(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i
    end
  end
end
# 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
(http://www.marklunds.com/articles/one/312), 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
cynthia.kiser-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---