Presenter Rescue Template
application / helpers / application_helper.rb
This will give you convenient access to a presenter instance anywhere in any of your presentations.
For example, if you use present @document , it will create an instance of DocumentPresenter .
module ApplicationHelper def present object, klass = nil klass ||= "#{object.class}Presenter".constantize presenter = klass.new object, self yield presenter if block_given? presenter end end
To override the presenter used, you can do present @document, MyPresenter
application / Presenters / document.rb
Your actual speaker. Create as many instance methods as you want and save all the presentation logic here. You have access to all helper viewing methods via @template
class DocumentPresenter def initialize document, template @document = document @template = template end def name if @document.template.name == "Newsletter"
application / views / document / show.html.erb
<% present @document do |document_presenter| %> <div id="document"> <%= document_presenter.description %> <%= document_presenter.name %> </div> <% end %>
Result
<div id="document"> <p class="description"> lorem ipsum </p> <a href="/newsletters">Newsletters</a> </div>
You can learn more about the presenter template, as Ryan Bates did in his RailsCast episode “Presenters from Scratches ”
source share