Interpret newlines as <br>s in markdown (Github Markdown-style) in Ruby Interpret newlines as <br>s in markdown (Github Markdown-style) in Ruby ruby ruby

Interpret newlines as <br>s in markdown (Github Markdown-style) in Ruby


I'm not sure if this will help, but I just use simple_format() from ActionView::Helpers::TextHelper

ActionView simple_format

my_text = "Here is some basic text...\n...with a line break."simple_format(my_text)output => "<p>Here is some basic text...\n<br />...with a line break.</p>"

Even if it doesn't meet your specs, looking at the simple_format() source code .gsub! methods might help you out writing your own version of required markdown.


A little too late, but perhaps useful for other people. I've gotten it to work (but not thoroughly tested) by preprocessing the text using regular expressions, like so. It's hideous as a result of the lack of zero-width lookbehinds, but oh well.

# Append two spaces to a simple line, if it ends in newline, to render the# markdown properly. Note: do not do this for lists, instead insert two newlines. Also, leave double newlines# alone.text.gsub! /^ ([\*\+\-]\s+|\d+\s+)? (.+?) (\ \ )? \r?\n (\r?\n|[\*\+\-]\s+|\d+\s+)? /xi do  full, pre, line, spaces, post = $~.to_a  if post != "\n" && pre.blank? && post.blank? && spaces.blank?    "#{pre}#{line}  \n#{post}"  elsif pre.present? || post.present?    "#{pre}#{line}\n\n#{post}"  else    full  endend