Pairing Tour: Working with Presenters
I kicked off the second week of my pairing tour with Skim, who’s been working on a big app upgrade for a client for the better part of the past year.
In the morning we updated a set of attributes from previously assigned values to a new range of values. This meant we also needed to update the way queries were made on those values, but the previously written tests guided us pretty well. It was the first time I’d ever seen elastic search in action and a great intro to both the power and complexity of it.
In the afternoon we helped one of the client’s designers update a view and it was my first chance to work with presenters in Rails. I’d read about presenters in various articles and seen them in one of 8th Light’s internal apps, but I never quite understood them. It’s amazing how much easier it is understand something when you have a guide along the way. Within a few minutes of working on it with Skim I was able to get a feel for how presenter’s work and why it makes sense to use them. Here’s a very over-simplified example of one:
In a traditional Rails controller you could have an action like this to set up variables for your views:
def show
@user = current_user
@course = current_user.courses.last
render :show
end
Then in your views you might have some logic like this:
<% if @user.freshman? %>
“Welcome to your first year”
<% elsif @user.senior %>
“Congrats on your final year”
<% end %>
This class is offered by the <%= @course.department.name %> department.
However, by using the presenter pattern you could strip the logic out of your view, limit the amount of digging into an object a view needs to do, and also slim down your controller. What the presenter boils down to is an object that encapsulates what you actually need for your view. Here’s how it would look:
#in the controller
def show
@presenter = CoursePresenter.new(@user)
render :show
end
#in the view
<%= @presenter.welcome_message %>
This class is offered by the <%= @presenter.course_department_name %>
Again, this is a very over-simplified example and wouldn’t necessarily call for creating an entirely new CoursePresenter class. However, if you found yourself setting a lot of variables in your controller action and/or using a lot of logic in your views hopefully it helps illustrate how you could use a presenter