Rails Presenters

Hey guys,

I’m wondering how you go about building your presenters in rails, and do you expose rails view helpers into your presenters? if so, how?

I’m trying to come up with a solution, and I think I’ve got one, but not sure how good of a pattern it is.

I’m thinking about creating an ApplicationPresenter and have all presenters inherit that presenter to expose rails view helpers there.

What are your thoughts?

I typically use the Draper gem, which is pretty fantastic for this. It has built in support for using helpers in your presenters.

Good question. I don’t have an actual answer to the first two questions, but here are my thoughts:

  • I try to shy away from html in presenters where possible, but certainly it is useful to build the html there sometimes and there’s nothing inherently wrong with it.
  • Presenters are great candidates for inheriting from SimpleDelegator. I imagine an inheritance chain of SomePresenter < ApplicationPresenter < SimpleDelegator is possible.
  • But others I know like to use BasicObject as the parent of presenters.

@lifeiscontent I agree with Caleb on this. SimpleDelegator is a good start when you’re decorating objects and are not in need of some of the features of Draper (eg: decorating collections).

Here’s something I just pulled up from a little side project of mine as an example on how to use SimpleDelegator:

class MessageboardDecorator < SimpleDelegator
  attr_reader :messageboard

  def initialize(messageboard)
    @messageboard = messageboard

  def category_options
    messageboard.categories.map { |cat| [cat.name, cat.id] }

  def users_options
    messageboard.users.map { |user| [user.name, user.id] }

In the chance you need to evolve or grow into Draper, the refactoring of your decorators/presenters shouldn’t be all that bad.

Hope this helps.

1 Like

Hey @joel quick question, how would you access messageboard.created_at for example, without using method_missing? or is that the only way to expose those methods to the view?

I think in @joel 's example that is being taken care of in the initializer, by passing the messageboard object. SimpleDelegator then forwards all supported methods to that object. You can read about how SimpleDelegator works in the docs.