by Ryan Walker

Use presenters and helpers for clean views

I’m working on this view:

Screenshot of My Profile in Job board project

Since we’re trying to encourage registration, I want to show certain fields, even if the user hasn’t filled out the information yet, to encourage them to complete the profile.

Here’s how a view may look without presentation pattern or helpers:

<ul class="contact-information">
  <li class="name">
    <label>Name</label>
    <b><%= @candidate.name %></b>
  </li>
  <li class="phone">
    <label>Phone</label>
    <b><%= @candidate.phone ? @candidate.phone : "Not provided" %></b>
  </li>
  <li class="work-interests">
    <label>Work Interests</label>
    <b><%=
      if @candidate.work_interests
        @candidate.work_interests.map { |wi| wi.name }.join ", ")
      else
        "None selected"
      end %></b>
  </li>
</ul>

Here’s what it can look like with them:

<ul class="contact-information">
  <%= profile_detail "Name", @candidate.name %>
  <%= profile_detail "Phone", @candidate.phone_text %>
  <%= profile_detail "Work Interests", @candidate.work_interest_names %>
</ul>

Presenter code:

class CandidatePresenter < CachingPresenter
  presents :candidate

  def phone_text
    return "Not provided" if @candidate.phone.blank?
    @candidate.phone
  end

  def future_work_interests_names
    return "None selected" if @candidate.future_work_interests.empty?
    @candidate.future_work_interests.map { |fwi| fwi.name }.join ", "
  end
end

Yes, you could build these presentation methods into the model, but that really clutters up the model. Yes, one more layer in the stack, but tossing this sort of stuff into the model really clutters it up, and ActiveRecord is already doing perhaps too much.

Helper code:

module CandidateDashboardHelper

  def profile_detail(label,value)
    return if value.blank? || label.blank?
    "<li class=\"#{label.downcase.dasherize}\"><label>#{label}</label><b>#{value}</b></li>"
  end
end

The libary we’re leveraging is Mutually Human’s fork of Zach Dennis’s Caching Presenter. (Hi Mark, Zach, Craig, and John!)


Filed under Ruby on Rails