Tuesday, February 6, 2007

Faux Accessors

Handy Rails technique from Josh Susser.

Basically, it gets around the fact that you can't override #initialize in an ActiveRecord model. The example he gives is actually better design than overriding #initialize anyway, but there's a potential for misuse there as well. The basic idea is, you can't override #initialize, but if you assign any given attribute on creation, you can override that attribute's #attribute= method, so you put your extra logic there.

The risk, of course, is that in some cases, you're doing something smart -- like if you have a #fullname= method assign first_name and last_name attributes based on splitting the fake "fullname" attribute -- but in other cases, in the case of misuse, you could wind up with code where all kinds of initialization stuff is done by depending on side effects. So, definitely a handy technique, but one with an air of living dangerously.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.