Where should Rails 3 custom validators be stored?
Asked Answered
S

4

96

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?

Savoyard answered 10/3, 2011 at 17:14 Comment(1)
How about changing the accepted answer flag?Sawdust
W
223

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

Width answered 7/7, 2011 at 12:3 Comment(5)
I don't know if there's some gem/config you need to add for this, but under rails 3.2.8 this doesn't work. Specifically, simply dropping your validator into app/validators/???.rb doesn't work.Amateur
Doug try to name the validator file same way the validator class is named but underscored: MyCoolValidator goes to app/validators/my_cool_validator.rbElrod
@Amateur you need to restart your server. The autoload paths are expanded on initialization so new subfolders will not get picked up until you do that.Aruwimi
I like to also monkeypatch ActiveModel::Validations::HelperMethods to add a helper for my new validation (e.g. validates_address for AddressValidator). When I include both the monkeypatch and the Validator in app/validators/address_validator.rb only the AddressValidator object is loaded, not the monkeypatch. Are you guys experiencing the same behavior?Restharrow
spring stop was necessary for me in Rails 5.2, otherwise it wasn't picked up.Secrecy
P
15

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.

Pietje answered 8/4, 2011 at 21:16 Comment(1)
Good idea but your code needs some cleanup: config.autoload_paths += %W(#{config.root}/lib/validators/)Ridgley
K
6

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

Kinser answered 10/3, 2011 at 17:18 Comment(0)
I
4

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

Inviolate answered 10/3, 2011 at 17:16 Comment(4)
Unless they're applicable to multiple models, in which case you should keep them elsewhere to stay DRY.Kwang
Which is what they presumably are because otherwise there's little point in creating a separate class for them.Kinser
@Jakub Yes there is: Single Responsibility PrincipleVicechairman
The link to the official docs is broken. Here is the current location of that documentation; guides.rubyonrails.org/…Cyclograph

© 2022 - 2024 — McMap. All rights reserved.