Created
November 28, 2008 09:04
-
-
Save henrik/29950 to your computer and use it in GitHub Desktop.
Like Rails' simple_format but avoids <p>/<br /> around some block tags.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From Rails | |
def simple_format(text, html_options={}) | |
start_tag = '<p>' | |
text = text.to_s.dup | |
text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n | |
text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph | |
text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br | |
text.insert 0, start_tag | |
text << "</p>" | |
end | |
# Like Rails' simple_format, but avoids e.g. <p><h4> and <br /><blockquote>. | |
# Only handles those two elements since that's all we need. | |
def unsimple_format(text) | |
text.gsub(/\r\n?/, "\n").split(%r{(\n*(?:<h4>.*?</h4>|<blockquote(?: .*?)?>.*?</blockquote>)\n*)}im).map do |part| | |
case part | |
when /\A\s*\Z/, /<h4>/ | |
part | |
when /blockquote/ | |
part.sub(%r{(<blockquote(?: .*?)?>)(.*?)(</blockquote>)}im) { $1 + simple_format($2) + $3 } | |
else | |
simple_format(part) | |
end | |
end.join | |
end | |
puts unsimple_format(DATA.read) | |
__END__ | |
x | |
<h4>Halloa</h4> | |
s | |
<h4>Aloha</h4> | |
more space | |
<blockquote cite="Pelle"> | |
foo | |
</blockquote> | |
bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment