Search⌘ K
AI Features

Using Presenters

Explore how to implement presenters in Rails using SimpleDelegator or the draper gem to manage view logic more cleanly. Learn to convert helper methods into presenter methods and write simplified tests that run faster without Rails dependencies.

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:

Ruby
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 ...