Where should Rails 3 custom validators be stored?

Ruby on-RailsValidationCustomvalidator

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

lib/validators seems by far the cleanest. However you may need to load them in before your models, so probably from an initializer.

Solution 4 - Ruby on-Rails

Here's the official docs about custom validations. AFAIK its a good practice to keep them in the relevant models.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel DView Question on Stackoverflow
Solution 1 - Ruby on-RailsgbcView Answer on Stackoverflow
Solution 2 - Ruby on-Railsgunit888View Answer on Stackoverflow
Solution 3 - Ruby on-RailsJakub HamplView Answer on Stackoverflow
Solution 4 - Ruby on-RailsShreyasView Answer on Stackoverflow