Sharing model validation code in lib/, how do I do this?

Hello everyone,

I’m having a bit of difficulty finding out the proper way to mix in code that I put into the lib/ directory for Rails 2.3.5.

I have several models that require phone validation. I had at least three models that used the same code, so I wanted to keep things DRY and moved it out to the lib/ directory. I used to have code like this in each model:

validate :phone_is_valid

Then I’d have a phone_is_valid method in the model:

protected

def phone_is_valid

process a bunch of logic

errors.add_to_base(“invalid phone”) if validation failed

end

I moved this code out into lib/phones/ and in lib/phones I have lib/phones/phone_validation.rb, and in there I copy pasted the phone_is_valid method.

My question is, how do I mix this into all of my models now? And does my validate :phone_is_valid method remain the same or does that change? I want to make sure that the errors.add_to_base method continues to function as it did before while keeping everything DRY. obviously the following won’t work:

validate :Phones::PhoneValidation::phone_is_valid(number)

I also created another file in lib/phones/ called lib/phones/phone_normalize.rb. Again, many models need the value input by the user to be normalized. Meaning turn (555) 222-1212 to 5552221212 or something similar. Can I invoke that simply by invoking Phones::Phone_Normalize::normalize_method(number)?

I suppose I’m confused on the following:

  • How to use the lib directory for validation of multiple models that need access to a particular validation method

  • How to use the lib directory for commonly shared methods that return values

Thanks for the help,

Matthew.

Maybe the following will help you …

6 Creating Custom Validation

Methods … http://guides.rails.info/activerecord_validations_callbacks.html
and/or …

http://marklunds.com/articles/one/312