Last Updated: February 25, 2016
·
19.49K
· ch4s3

Turn a new line(\n) into a <\br> tag with Ruby

Rails or more specifically ActionView has a method simple_format which translates escape characters into html tags and can turn arbitrary user input tags into html. Ruby doesn't have a standard lib equivalent, and sometimes you only want to allow certain tags. In those cases, creating a simple line break helper may be useful. It may look like:

Straight Ruby

module LineBreak
  def break_the_lines(text)
    text.to_s.gsub(/\n/, '<br/>')
  end
end

Throw an include where you need the method and you're good to go.

Rails Version

module LineBreak
  def break_the_lines(text)
    text.to_s.gsub(/\n/, '<br/>').html_safe
  end
end

Place this in /helpers and you're set.

I used .to_s to ensure that gsub can be used and the method will not be broken by an array of strings.

The method .html_safe is a method on String
that creates a new ActiveSupport::SafeBuffer and flags it as @dirty. This tell Rails that its ok to render any unescaped html in the string.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip