Tuesday, January 8, 2008

Presenter classes help with Rails complexity

A few weeks back I gave a talk at a Bmore on Rails meeting all about Presenter classes, which I learned about from Jay Fields.  I can't claim any authorship of this idea, but it's been very helpful to me, so I thought I'd share some of my examples here plus a bit of extra code I wrote to make Presenter integration with ActiveRecord a bit more fun.

Presenters allow you to extract the logic needed for complex views (especially views that require the use of more than one model) into a separate, easily testable class.  This helps you write clean code and skinny controllers, among other benefits. 

1) The key background material is here:

2) I extended Jay Fields' code by adding methods to combine error messages from different models:

3) An example Presenter, combining a User object and an Account object into a Preference presenter, is here:

4) An example controller, using the Preference presenter, is here:

Also, Jay wrote an excellent recipe for Advanced Rails Recipes that covers this technique.