martincarlin87
martincarlin87

Reputation: 11062

Rails convention for case statement in view

I am new to ruby and rails so thought I'd ask a question on conventions.

I have a view which produces a list of items in a table and I was asked to make a change and in doing so have added a case statement to the view which I don't think is the correct way of doing things so thought that I would double check.

The change I made was just to add a class to the tr depending on the value of the last table column.

list.rhtml

<table width="100%">
    <tr>
        <th style="width: 80px;">ID #</th>
        <th>Organisation</th>
        <th>Product</th>
        <th>Carrier</th>
        <th>Carrier Ref</th>
        <th>Post Code</th>
        <th>Status</th>
    </tr>

    <%= render :partial => 'circuit/list_item', :collection => @circuits %>

</table>

list_item.rhtml

<%
# code I have added
@tr_class = ''

case list_item.status
when 'Handover'
  @tr_class = ''
when 'Unprocessed'
  @tr_class = 'high_priority'
when 'Ceased'
  @tr_class = 'low_priority'
else
  @tr_class = ''
end
# end of newly added code
%>

<!-- the class part is new aswell -->
<tr class="<%= @tr_class %>">
    <td><a href='/circuit/update/<%= list_item.id %>'><%= list_item.id_padded %></a></td>
    <td><%= list_item.organisation.name if list_item.has_organisation? %></td>
    <td><%= list_item.product_name %></td>
    <td><%= list_item.carrier.name %></td>
    <td><%= list_item.carrier_reference %></td>
    <td><%= list_item.b_end_postcode %></td>
    <td><%= list_item.status %></td>
</tr>

Is there a Rails pattern or convention that can get the case statement out of this view?

Upvotes: 0

Views: 480

Answers (1)

toro2k
toro2k

Reputation: 19238

If understand properly your question, I think you should put the case statement inside a helper function:

app/helpers/list_helper.rb

module ListHelper
  def tr_class_for_status(status)
    case status
    when 'Unprocessed'
      'high_priority'
    when 'Ceased'
      'low_priority'
    else
      ''
    end
  end
end

_list_item.rhtml

<tr class="<%= tr_class_for_status(list_item.status) %>">

Upvotes: 4

Related Questions