How do I run multiple lines of Ruby in html.erb file

ben picture ben · Jun 23, 2010 · Viewed 40.1k times · Source

I'm using Ruby on Rails and need to run a block of Ruby code in one of my html.erb files. Do I do it like this:

<% def name %>
<% name = username %>
<%= name %>

or like this:

<% def name
name = username %>
<%= name %>

Thanks for reading.

Answer

nathanvda picture nathanvda · Jun 23, 2010

If you need extra functions in your view, you normally declare those inside a helper.

For each controller, if there is a helper it is automatically loaded. For instance, if you have a PeopleController, in the app/helpers folder, there should be a people_helper.rb, and it should look like this

module PeopleHelper
  def name
    #do something
    username
  end
end

Another, very clean alternative, is to use the Presenter pattern, but i think it is less common (unfortunately).

Otherwise, if you do need multiple lines of ruby code inside a erb view, which i try to avoid, i prefer the following style:

<%
   counter_1 = 0
   counter_2 = 1
   do_some_more_prep_here
 %>
<% @records.each do |rec|%>
  <%# do something with the prepped date in each row %>
<% end %>

Also for me code indentation is more important than html indentation, so i will prefer something like

<table> 
  <% @rows.each do |row| %>
    <tr>
      <td><%= row.item1 %></td>
      <% if row.some_test %>
        <td><%= row.item2 %></td>
      <% end %>
    </tr>
  <% end %>
</table>

But i am always very interested to hear different opinions in this matter.