Posted 3 months ago. Visible to the public. Repeats.

When you want to format only line breaks, you probably do not want simple_format

For outputting a given String in HTML, you mostly want to replace line breaks with <br> or <p> tags.
You can use simple_format, but it has side effects like keeping some HTML.

If you only care about line breaks, you might be better off using a small, specialized helper method:

def format_linebreaks(text) safe_text = h(text) paragraphs = split_paragraphs(safe_text).map(&:html_safe) html = ''.html_safe paragraphs.each do |paragraph| html << content_tag(:p, paragraph) end html end

Full disclosure: Under the hood this uses the private Rails helper method split_paragraphs that simple_format uses.
While it might break when upgrading Rails, you at least don't need to re-implement that part.

Note that calling map(&:html_safe) is okay because we escaped the input, and because splitting it won't turn the escaped input unsafe.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Arne Hartherz
Last edit:
3 months ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more