In Rails - is there a rails method to convert newlines to <br>?

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

Currently, I'm doing it like this:

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

Solution 1:

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#method-i-simple_format

Example:

 simple_format(mystring)

Note that simple_format allows basic HTML tags, but also passes text through sanitize which removes all scripts, so it should be safe for user input.

Solution 2:

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.

Solution 3:

You should be careful with this when you are dealing with user input.
simple_format inserts <br> tags but it will allow other html tags!

When using simple_format, <b>Hello</b> will be rendered as "Hello", you might not want this.

Instead you can use <%= h(c.text).gsub("\n", "<br>").html_safe %>
h() will encode the html first, gsub replaces the line break and html_safe allows the <br> tags to be displayed.

This will display exactly what the user entered. It also allows to discuss html in e.g. comments.