Multi line text

Hi,

I am storing multi-lined information in a text field in the database,
and intaking it using a text_area field. When i output it, the
information is all streamed into one line. How can I output the
information with the line breaks.

Thanks!

Replace ‘\n’ with ‘
’ (or ‘
\n’) in your string when rendering it.

Cheers.

I define the following method in one of my helper files:

  # wraps each line to width characters, splitting lines on a
whitespace character
  def wrap_text(text, width = nil)
    char_count = 0
    0.upto(text.length) do |i|
      point = i;
      # reset the character counter if we encounter a newline
      # before we've reached width characters
      char_count = 0 if text[point..point] == "\n";
      if char_count > width
        # once we hit the desired width of characters, start
        # moving backwards one character at a time until we
        # encounter a whitespace character
        point -=1 while text[point..point] != " "
        text.insert(point+1, "\n")
        # we've inserted a newline, reset the character counter
        char_count = 0;
      else
        char_count+=1
      end
    end
    return text
  end

I'm sure there's an easier method for line wrapping (if anyone else
has a better method, I'd love to see it). I did come across the
following site earlier today, which includes a _much_ simpler method
for line wrapping, although unfortunately it doesn't work:

http://redhanded.hobix.com/inspect/methodCheckDateSucc.html

the method is the following:

str = "Hello. Ruby rocks. " * 50
while space_pos = str.rindex(" ", 80)
  str[space_pos, 1] = "\n"
end

but it fails to correctly line wrap, since each call to str.rindex
doesn't take into account where the previous newline character was
inserted.. I just didn't want to spend any time fixing it, since I've
already got a working line wrap method (albeit mine is a bit
cumbersome).

Mike

Thanks Curtis, that's good to know.. Although I think I'll stick to my
current method, as this one seems to remove lines with nothing but a
line feed on them, which I often have, since I'm displaying the
contents of user entered text in a <pre></pre> tag. With my method, I
get pretty much exactly what the user has entered, including their
empty linefeeds, but wrapped so that it doesn't extend past the width
of the page.

Mike

Thanks for all the help! I ended up using the simple_format helper as a
base, but modified it so that it didn't put <p> tags around the entire
thing.

  def simple_format2(text)
    text.gsub!(/(\r\n|\n|\r)/, "\n") # lets make them newlines
crossplatform
    text.gsub!(/\n\n+/, "\n\n") # zap dupes
    text.gsub!(/\n\n/, '</p>\0<p>') # turn two newlines into paragraph
    text.gsub!(/([^\n])(\n)([^\n])/, '\1\2<br />\3') # turn single
newline into <br />
  end

Thanks again!