Presenters are a type of decorator used to reduce complexity of view templates. We’ll get to the core of what a decorator is at the end, but to start with, let’s give an example of a presenter. In Rails, install the “Draper” gem and create a presenteer for an associated model. Eg:
rails generate decorator SomeTestModel
Then, generate the following decorator:
class BookDecorator < Draper::Decorator
delegate_all
def book_sequel_link
if book_sequel
h.link_to(book.sequel.title, book.sequel).html_safe
else
'No sequels'
end
end
public_email ? email : h.link_to('Request Email', '#', class: 'btn btn-default btn-xs').html_safe
end
def friendly_author_format
authors.join(', ')
end
end
In the controller, you would then add .decorate
to the end of the call to the model (Eg: @book = Book.find(params[:id]).decorate
) to provide access to the above methods.
In presenters, you can access view helpers (eg: see the “h.link_to”) above in a way you can’t should you put this logic in the model. Ultimately, they allow you to separate out complex view logic from templates, while still having access to Rails’ view helpers.
Presenters are the view-focusing implementation of decorators, which serve the broader purpose of providing extra functionality to a specific instance of a class when (and only when) the decorator is instantiated. So while this above presenter is a decorator for views, you could also decorate a class for other non-view reasons, which would fall under the broader category of ‘decorator’