I would like to make a presenter for the Event
index view, which currently iterates through all events like this:
<% @events each do |event| %>
<td><%= link_to event.name, event_path(event) %></td>
<% end %>
there will be many other things in there, but this is the gist of it. I want to be able to do something like:
<% present @events do |event_presenter| %>
<td><%= event_presenter.event_title %></td>
<% end %>
the EventPresenter
would be subclass of the BasePresenter
, taken from Railscast 287
class BasePresenter
def initialize(object, template)
@object = object
@template = template
end
private
def self.presents(name)
define_method(name) do
@object
end
end
def h
@template
end
def markdown(text)
Redcarpet.new(text, :hard_wrap, :filter_html, :autolink).to_html.html_safe
end
def method_missing(*args, &block)
@template.send(*args, &block)
end
end
What confuses me is that in the Railscast the example is for show action, not index action. There are no iterations in the view like @events each do |event|
. You can't just stick the method into the presenter file this way:
def event_title
link_to event.name, event_path(event)
end
I generally manage this thing more manually, i find it easier to handle that way and reason about exactly what is going on when i need to change something or debug.
Anyway, the way that i do that is normally in the controller.
def index
@events = Event.all.map(|event| EventPresenter.new(event))
end
Then in your views they are already mapped over to what you are needing.