Is there a Railsy way to convert \n to <br>
?
Currently, I'm doing it like this:
mystring.gsub(/\n/, '<br>')
Is there a Railsy way to convert \n to <br>
?
Currently, I'm doing it like this:
mystring.gsub(/\n/, '<br>')
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.
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.
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.
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)