Skip to content

Instantly share code, notes, and snippets.

@avdgaag
Created October 23, 2009 12:22
Show Gist options
  • Save avdgaag/216842 to your computer and use it in GitHub Desktop.
Save avdgaag/216842 to your computer and use it in GitHub Desktop.
Mark up plain text lines as HTML lists
def to_list(text)
ol_prefix = /^\d+\.?\s*/
dl_prefix = /^(.+):\s*/
ul_prefix = /^[^\s]+\s*/
lines = text.split("\n").map { |line| line.strip }
if lines.any?
tag, pattern = if lines.first =~ ol_prefix
['ol', ol_prefix]
elsif lines.first =~ dl_prefix
['dl', dl_prefix]
else
['ul', ul_prefix]
end
"<#{tag}>\n%s</#{tag}>" % lines.inject('') do |output, line|
if pattern == dl_prefix
output += "\t<dt>%s</dt>\n\t<dd>%s</dd>\n" % [line[pattern, 1], line.gsub(pattern, '')]
else
output += "\t<li>%s</li>\n" % line.gsub(pattern, '')
end
end
else
text
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment