Monday, August 07, 2006

Rails Aggregations Ready for Prime Time?

Aggregation (or composition) of database fields into value objects in Rails has given me some fits lately. While a valuable abstraction, it unfortunately does not yet cohabitate nicely enough with the rest of Rails to make them painless.

Using the example from section 15.2 in "Agile Development with Rails", a Name is a group of three fields (first, initial, last) that is used in a Customer. Great. The Customer uses the composed_of method and you can do things like name.first, name.last, and call methods you might define in Name. All is well... that is until you start using it in the framework, say for example for validation or within views.

Let's say, for instance, that a name needs to be unique within your system. Not necessarily a completely valid constraint perhaps, but good enough for argument's sake. Well, you can't do a validates_uniqueness_of :name to indicate that you always have a unique combination of first name, initial and last name because the validation doesn't play nicely with composites. Names just don't expand correctly inside the validators - code to handle this case is still missing.

Ok, let's consider views. say you want to use the last name in a text field - you can't specify because name.last isn't an attribute, although it's certainly standing in for one. The attribute string mapping is just not robust enough for within the framework.

No, sorry, though aggregation is sweet, the mix within Rails isn't there yet. It's unfortunate since the mechanism could be so clean. To do what's needed today, you just have to slice up the problem differently and using composites outside of the model. I guess these are the growing pains that will shake out over time.

No comments: