Generic-user-small Keyton Weiss... 1 post

OK. So I’m a noob in both Rails and Ruby—but I’m trying to migrate and approach the code from a Ruby perspective.

As such, in the Instant Gratification Fun Time section, I tried the following (to do a bit better in the “looks like Ruby” category than the example):

<% if @files %>
    <h1>Files or Directories 2</h1>
    <ul>
      <%= @files.each {|file|}%>
    </ul>
    <% end %>

OK. No problem. That works. I get (or similar) in the resulting HTML:
Files or Directories 2
appcomponentsconfigdbdocliblogpublicRakefileREADMEscripttesttmpvendor

But if I want to add a little markup:

    <% if @files %>
    <h1>Files or Directories 2</h1>
    <ul>
      <%= @files.each {|file| puts '<li>'+file+'</li><br/>'}%>
    </ul>
    <% end %>

I get the exact same thing in my resulting HTML page (i.e. no markup):
Files or Directories 2
appcomponentsconfigdbdocliblogpublicRakefileREADMEscripttesttmpvendor

I’ve tried it in IRb to make sure the Ruby itself acts the way I think it should (and to make sure I wasn’t making a stupid Ruby mistake). But that worked fine.

What up?

Thanks in advance.

Keyton Weissinger

 
Generic-user-small Don Bessinger 9 posts

I’m in the same boat you are as far as learning both Ruby and Rails, and I played around with the same things to make nicer formats. It looks like you’ve tried to include HTML tags within the <% ... %> brackets. Ruby expects everything in there to be Ruby code, so try moving the HTML tags out. Something like this may work:


<% if @files %>
  <h1>Files or Directories 2</h1>
  <ul>
    <li><%= @files.each {|file| puts file} %></li><br/>
  </ul>
<% end %>

That’s untested, but you get the idea – keep that Ruby and HTML separate.

 
Generic-user-small Timothy Knight 3 posts

Well, if we are talking Rails, why not use the content_tag helper here? Remember each item needs to be surrounded by an (li) and there is no need for a (br) after each item. Perhaps there is a one line way of doing this, but doing a block works just fine for me.


<% unless @files.nil? %>
    <h1>Files or Directories 3</h1>
      <ul>
            <% @files.each do |file| %>
                <%= content_tag :li, file %>
            <% end %>
      </ul>
<% end %>
 
Generic-user-small Fredrik W 3 posts

I think you’re getting the error because you’re using the “puts” method inside of a view template.

<% @files.each do |file| %> <= ‘

  • file
  • ’ %>
    < end %>

    should probably work, even if the latter solution proposed by timothy is more elegant.

    http://railscasts.com/episodes/40 might interest you as well. It discusses how you can refactor blocks into helper methods that accepts blocks and how to go about with that.

    4 posts, 4 voices