Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should Rails 3 custom validators be stored?

I've seen docs/websites show that custom validators should go in a /lib or /lib/validators directory of a project. I've found (by reading an answer to another post) that they only seem to work in config/initializers. Does anyone know, or have a pointer to official documentation that shows where custom validators should live?

like image 926
Daniel D Avatar asked Mar 10 '11 17:03

Daniel D


People also ask

What methods should you implement for your custom validator?

Implementing the Validator Interface A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.

How do I create a custom validator?

Custom validators take the value from the FormControl , where every input acts as a FormControl . So let's create a form along with a validator function. Create a new file called customvalidator. validator.


2 Answers

If you place your custom validators in app/validators they will be automatically loaded without needing to alter your config/application.rb file.

like image 196
gbc Avatar answered Oct 18 '22 20:10

gbc


If you add this to your /config/application.rb file:

config.autoload_paths += %W["#{config.root}/lib/validators/"] 

Then Rails will automatically load your validators on start up (just like /config/initializers/), but you keep the clean structure of having your validators in one nice, well named spot.

like image 39
gunit888 Avatar answered Oct 18 '22 20:10

gunit888