Simple Presenters & Decorators on Rails

There's been a lot of talk aboutdecorators and presenters (which are almost the same) in Rails and how they help you with a "real" OO code. There are great gems and there's even a Railscast (pro) on how to build a presenter from scratch. But, in the new project I'm working on, we (<- he) has this really simple setup which I feel kind of cleaner.

What we wanted to have was a present method in the controller and build the view from its methods. So, we created an ActiveSupport::Concern called Presentable and included it in our application controller. Here's our (once again, his) code for that module.

Now, we just need to create each presenter. But, since there's a lot of shared logic between presenters we (he) just created a parent Presenter class with all that. Notice that our presenter takes an object as parameter, so we just delegated all the method calls to our record (thank you method missing) if it responded to that method. You could also send the view context to access Rails helpers inside your presenter. Here's our Presenter base class.

Then, we just need to inherit from the Presenter class and add our custom, clean methods. Using delegate and method missing will help us keep the class clean. I won't show you a presenter here, they'll look a lot like Ryan's one in his Railscasts so check that out first.

I will show you our controller though. Using the decent_exposure gem we managed to get super tiny controllers. Here's 1 of them:

Combining presenters and form builders will make your views even cleaner, giving a lot of pleasure to the future you! So please, just pretty-please, start using presenters and builders and leave helpers as simple as possible. Or, leave them for good.

You'll be amazed how different you'll feel when reading some old code or some co-worker's code.