Search code examples
ruby-on-railsspacingreadlines

IO.readlines with spaces included - Ruby on Rails


I'm new to Rails and I've a problem and I have no idea how to solve it. Tried with google but with no luck.

Basically I have a textfile that I use IO.readlines to read the file, put in an array and then have it printed out in my View. I got that working.

The problem is that the textfile I "read" have indentations and when I print it out in my view from the array the indentation spaces dont get included.

This is how the code looks like at the moment.

Controller

 @codefile = Codefile.find(session[:codefile_id]) 
  dir = @codefile.file.url.to_s 
  url = dirr.split("?")
  @fileLinesArray = IO.readlines('public' + url[0]) 

View

<ol>
<% @fileLinesArray.each do |x| %>
    <li><%= x %></li>
<% end %>
</ol>

Maybe I'm not even supposed to use readlines? Anyway...
Very thankfull for any help I can get!


Solution

  • Your problem is HTML ignores multiple spaces in code. If you check the HTML source you'll see the spaces are there but they aren't rendered.

    You have to use the <pre> tag, which stands for "preformatted" to preserve whitespace:

    <ol>
    <% @fileLinesArray.each do |x| %>
        <li><pre><%= x %></pre></li>
    <% end %>
    </ol>
    

    Also you'll probably want to change it to <%= x.chomp %> which will leave off the extra newline character.