views:

194

answers:

2

Hey,

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.

+1  A: 

It's really wired to define a method in ERB file and really don't advice.

If you want call a block like #each you can do :

<% names.each do |name| %>
  <%= name %>
<% end %>

You forget the end.

shingara
and you forgot a `|` after `|name` ;-)
jigfox
+5  A: 

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.

nathanvda
Helper methods are the way to go, for sure.
tadman