I've got a Rails project where, as in most apps, we have a number of hard-and-fast validation rules to which all objects must conform before being persisted. Naturally, ActiveModel's Validations are perfect for that – we're using a combination of Rails defaults and our own hand-rolled validations.
More and more, though, we're coming up against use cases where we would like to alert the user to cases where, while their data is not invalid in the strictest sense, there are elements which they should review, but which shouldn't in themselves prevent record persistence from occurring. A couple of examples, off the top of my head:
- A post title has been submitted in ALL CAPS, which may be valid but probably isn't
- A pice of body text is more than x number of words less or more than a suggested word count
The validations module is such a good metaphor for how we treat validation errors – and has so many matchers already available – that ideally I'd like to be able to reuse that basic code, but to generate a collection of warnings
items alongside errors
. This would allow us to highlight those cases differently to our users, rather than implying that possible violations of house style are equivalent to more egregious, strictly enforced rules.
I've looked at gems such as activemodel-warnings, but they work by altering which matchers are checked when the record is validated, expanding or shrinking the errors
collection accordingly. Similarly, I looked at the built-in :on
parameter for validations to see if I could hand-roll something, but again all violations would end up in an errors collection rather than separated out.
Has anybody tried anything similar? I can't imagine I'm the only one who'd like to achieve this goal, but am drawing a blank right now...
ActiveModel::Errors
and use it as storage for your warnings – Euonymusrecord.errors.add(attribute, ...)
where you will needrecord.warnings.add(attribute, ...)
– Euonymus