2012-07-07 00:52:32 +02:00
|
|
|
class Markdowner
|
2013-03-24 03:05:13 +01:00
|
|
|
# opts[:allow_images] allows <img> tags
|
|
|
|
# opts[:disable_profile_links] disables @username -> /u/username links
|
|
|
|
|
|
|
|
def self.to_html(text, opts = {})
|
2012-07-07 00:52:32 +02:00
|
|
|
if text.blank?
|
|
|
|
return ""
|
2013-03-24 03:05:13 +01:00
|
|
|
end
|
|
|
|
|
2015-08-12 16:23:58 +02:00
|
|
|
args = [ :smart, :autolink, :safelink, :filter_styles, :filter_html,
|
|
|
|
:strict ]
|
2013-03-24 03:05:13 +01:00
|
|
|
if !opts[:allow_images]
|
|
|
|
args.push :no_image
|
|
|
|
end
|
2012-07-07 00:52:32 +02:00
|
|
|
|
2015-12-03 22:56:52 +01:00
|
|
|
ng = Nokogiri::HTML(RDiscount.new(text.to_s, *args).to_html)
|
|
|
|
|
|
|
|
# change <h1>, <h2>, etc. headings to just bold tags
|
|
|
|
ng.css("h1, h2, h3, h4, h5, h6").each do |h|
|
|
|
|
h.name = "strong"
|
|
|
|
end
|
2013-03-24 03:05:13 +01:00
|
|
|
|
|
|
|
# make links have rel=nofollow
|
2015-12-03 22:56:52 +01:00
|
|
|
ng.css("a").each do |h|
|
|
|
|
h[:rel] = "nofollow"
|
|
|
|
end
|
2013-03-24 03:05:13 +01:00
|
|
|
|
2015-12-03 22:56:52 +01:00
|
|
|
unless opts[:disable_profile_links]
|
2012-09-16 22:51:25 +02:00
|
|
|
# make @username link to that user's profile
|
2015-12-03 22:56:52 +01:00
|
|
|
ng.search("//text()").each do |t|
|
|
|
|
if t.parent && t.parent.name.downcase == "a"
|
|
|
|
# don't replace inside <a>s
|
|
|
|
next
|
2012-09-10 19:40:33 +02:00
|
|
|
end
|
2015-12-03 22:56:52 +01:00
|
|
|
|
|
|
|
tx = t.text.gsub(/\B\@([\w\-]+)/) do |u|
|
|
|
|
if User.exists?(:username => u[1 .. -1])
|
|
|
|
"<a href=\"/u/#{u[1 .. -1]}\">#{u}</a>"
|
|
|
|
else
|
|
|
|
u
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
t.replace(tx)
|
2012-09-10 19:40:33 +02:00
|
|
|
end
|
2012-07-07 00:52:32 +02:00
|
|
|
end
|
2013-03-24 03:05:13 +01:00
|
|
|
|
2015-12-03 22:56:52 +01:00
|
|
|
ng.at_css("body").inner_html
|
2012-07-07 00:52:32 +02:00
|
|
|
end
|
2012-09-16 22:51:25 +02:00
|
|
|
end
|