Having logic in your view is bad. Putting some in the helpers can help. Some methods can be put on the model. Sometimes, your view involves a couple of models, the helpers get bigger, you’re not sure on which model to put a method as it needs data on a few of the associations. The view is getting ugly, you have to go through pages of helper methods to find things. You’re feeling dirty.
Move all the methods related to one of the view to a class (the presenter). Create it in the controller by passing it all the objects it needs to manipulate. Change your view to only call methods on your @presenter.
You will probably want to have access to the ActionView::Helpers::* in your presenter so it can useful to declare a base presenter class you will inherit from like this:
Some helpers need the @controller to do their magic.
I’ve used this approach two times now. Last time, I had a view that showed deeply nested data (parent => children => children => children). There were a bunch a checkboxes that needed to be all checked/unchecked at the same time depending on which element was clicked. Putting all the methods required to generate the checkboxes with ids and class and restoring that from the params in case of an error was ugly. However, that ugliness was nicely sealed in a class that prevented infection of the rest of the code.
- Jay Fields Thoughts: RailsConf Europe 07: Presenter Links
- Simple Presenters
- Model View Presenter Pattern
- Jay Fields Thoughts: Rails: Rise, Fall, and Potential Rebirth of the Presenter Pattern
- Giles Bowkett: My Version Of Rails Presenters
The approach I described here may not fit the original presenter pattern as described in those other links. What’s important here is, if your view is getting ugly, hard to test, you have too many helpers, or the code is starting to smell, you can move stuff to a new class. This may seem evident, but I sometimes feel people using rails forget that you can do stuff “outside” of the way rails normally structure a project. Also note that the presenter pattern is definitely not something you need for every project.
Popularity: 10% [?]