Using Presenters

Learn about Ruby presenters, their helper methods, performance, and how to write tests using presenters.

View testing presenters

Testing helpers is handy, but if we have a lot of logic in the helpers, we recommend moving the logic into presenter objects. This is especially true if we have a series of helpers that take the same argument.

Ruby presenters

There’s nothing complicated about using presenters in Rails. We can use them using Ruby’s SimpleDelegator class. If we want a little more structure, we can use the draper gem.

We can convert the project helper to a project presenter. This version of the code uses SimpleDelegator and includes a method for converting a list of projects into a list of presenters. In a break from convention, we’ll show the code first:

Press + to interact
class ProjectPresenter < SimpleDelegator
def self.from_project_list(*projects)
projects.flatten.map { |project| ProjectPresenter.new(project) }
end
def initialize(project)
super
end
def name_with_status
dom_class = on_schedule? ? "on_schedule" : "behind_schedule"
"<span class='#{dom_class}'>#{name}</span>"
end
end

The main ...