Saturday, October 13, 2007

My Version Of Rails Presenters

Like Jay Fields, DHH, Jamis Buck, and Marcel Molina, I've cooked up a presenter implementation. I only know DHH and Jamis Buck did it through Jay Fields' blog, but I've looked at code for Jay's and Marcel's implementations, and I can tell you both those implementations are more sophisticated than mine.

In keeping with the rule that you do the simplest thing that could possibly work, my presenters have been plain old Ruby objects. Usually they start life as Structs and gradually morph into something larger. Eventually the Struct subclassing disappears and they get attr_accessor calls instead. Afterwards, they tend to wander a bit from the pure Presenter object path, in that they get all Seasidey on you and start returning HTML as well.

As cool as Seaside is, I think the smart thing to do in future will probably be to incorporate some of the metaclass magic in Marcel's version of presenters, which gives you access to both controller and helper methods from within the presenter, because even though I like the Seaside approach, passing off data to a render :partial might be more responsible and consistent. If everything else in the system uses templates, the presenters should generally use templates too.

However, I find that wrapping a render :partial call inside some other object, so that your view just contains something like @list.item, for instance, makes for code which is incredibly readable. If anything, I would be much happier pulling all the render :partial calls out of the view entirely. After all, there's no rule that your ERb templates have to contain HTML. You can just open up a <@= at the top of the file, put in a bunch of Ruby, and close it up again with another @> at the very end. As long as the Ruby code returns a string, you're good to go.

I've been meaning to post about this for a while, but I was just reminded by Jay Fields' post on extending Rails. Don't just use Rails. Own it.

No comments:

Post a Comment

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