Isolating Validations in ActiveModel
I’m working on a rails project where I’m experimenting with a much more object-oriented approach than Rails usually encourages. I’m intending on writing more in depth about that, when I can better gather my thoughts about the experience. I found something recently that I can write a brief post about and hopefully get the ball rolling.
I’m trying to keep a fairly hard-line divide between my persistence layer and the actual domain objects. What this means for today’s purposes is that my domain objects know nothing about ActiveRecord (and some of them never will).
This lead me to a philisophical quandry when trying to figure out validations. My domain objects are already imbuded with ActiveModel attributes, because they communicate with the view layer in ActionPack. (ActiveModel is, essentially, the reference API that ActionPack expects.) However, validations can cross both persistence and domain concerns. I’ve also been pretty heavily burned in the past by the mess that is conditional validations.
In debating whether to embed my validations in the domain model, or in the ActiveRecord objects that my Repositories map the domain entites to, I realized that I had a third option: Separate the validations. Structuring the validations as their own class opens up a lot of the traditional OO flexibility that I’ve been aiming for in this application, and allows me to ignore the validations in situtations where they are not needed, without a lot of stub/mock gymnastics.