I have blocks of pseudo-code text stored in a database that get printed off line-by-line and displayed in HTML.
Pseudo-code entered in text column in database:
while (counter <= 10) {
printf("Enter grade: ");
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
} /* end while */
Controller:
def index
@code = Code.first // just a filler for the time being
end
Index:
- @code.cont.each_line do |line|
- i += 1
.line
%span= i
%li.line= line
- i = 0
Somewhere along the way Ruby automatically strips out any whitespace and just leaves me with the text. I'd like to know how to preserve this so that
This:
while (counter <= 10) {
printf("Enter grade: ");
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
} /* end while */
Doesn't come out as this:
while (counter <=
printf("Enter grade: ");
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
} /* end while */
I'm pretty sure your space characters are there, but you can't see them due to the way HTML handles whitespace. Double check this by putting your text into a variable and dumping it to console with a simple puts my_chunk_of_text
. If the spaces are there (and I can't see why they wouldn't be, based on the code you posted), you have a couple of alternatives:
1) Sandwich your displayed text with the <pre>
tag, which renders preformatted text. You're going to want to do this in your view, like this:
<pre><%= @my_chunk_of_text %></pre>
2) Save the text in HTML format, with non-breaking spaces (
) wherever you want a space to appear, and <br>
where you need a newline. This code can be rendered in your view with the html_safe
helper.
<%= @my_chunk_of_text.html_safe %>