jgaskins/perpetuity — Issue #2: Validations
Author: jgaskins
Created: 2012-02-26 04:33:08+00:00
State: open

# Every ORM needs validations of some sort, right?

I'm not too sure about this, to be honest, because determining if an object is valid is pretty specific to the object. However, there are several possibilities.

## Collection-scoped versus object-scoped validations

Validations can be scoped at either the object or the collection level. In an object-scoped validation, the object's validity can be determined without looking at any other object in the collection. This refers to things like validating that a field isn't blank or that an e-mail address field is, in fact, formatted as an e-mail address.

On the other hand, collection-scoped validations have everything to do with the values of other objects in the collection. Uniqueness is an example of this sort of validation — and is, in fact, the only one I can think of off the top of my head.

## Ideas for object-scoped validations

Object-scoped validations seem best to leave to the class of the domain object, I think, but it would be nice to provide an easy way for them to ensure their validity.

A simple interface would be that the domain object's class defines a method called `valid?` that determines whether or not the object's data is as expected. If the object does not respond to that method, we could assume that it has no object-level validations.

## Ideas for collection-scoped validations

Collection-scoped validations could be done a few different ways. The first is listing the validations in an ActiveRecord-style `validates_X_of :attribute` fashion inside the mapper. This gets ugly pretty quickly if there are more than 2 or 3, though. But since I can't personally think of anything more than uniqueness at this scope, this is still a possibility.

If, however, we decide we need several validations at this scope, we can do something like:

```ruby
class ArticleMapper
validations do
unique :title
something_else :attr1
something_entirely_different :attr2
end
end
```

This both consolidates validations in the mapper (which we should be doing anyway) and gets rid of the ugly repetition of `validates_X_of` calls.

If anyone on the internets has any ideas, I'd love to hear them.