views:

1091

answers:

4

Is there a Railsy way to convert \n to <br>?

Currently, I'm doing it like this:

mystring.gsub(/\n/, '<br>')
A: 

Nope. What you have there is the commonly used alternative. The definition most people use is:

   def nl2br text
       text.gsub(/\n/, '<br/>')
   end

It is named as such because it mimics the functionality of the PHP function by the same name.

ryeguy
+1  A: 

You also might consider what you're trying to do - if you're nicely formatting text that people have entered, you might consider a filter like Markdown to let your users format their text without opening up the can of worms that is HTML. You know, like it is here at Stack Overflow.

Jim Puls
+1  A: 

You may make it more general by doing:

mystring.gsub(/(?:\n\r?|\r\n?)/, '<br>')

This way you would cover DOS, *NIX, Mac and accidental invalid line endings.

Tomalak
+11  A: 

Yes, rails has simple_format which does exactly what you are looking for, and slightly better since it also adds paragraph tags. See

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001719

Example:

 simple_format(mystring)
Daniel Von Fange
Thanks- I should have known this- I've used simple_format in other projects.
daustin777