4

My rails app is using RDiscount to generate HTML from user-supplied markdown text, and I noticed that the anchor tags don't have rel="nofollow". This is a big issue for me as my app is open to the public. Is there a way to enable nofollow links, or are there better solutions?

Thanks!

widgetycrank
  • 429
  • 4
  • 11

4 Answers4

3

I think this is possible only with Kramdown, which is a ruby Markdown parser with extended syntax. You would do that then as shown in the link:

[link](test.html){:rel='nofollow'}
farnoy
  • 7,356
  • 2
  • 20
  • 30
  • Actually the content will be supplied by the user, so I need a way to automatically add rel="nofollow" to every link as a measure to discourage SEO spam. I think stackoverflow does it. – widgetycrank Jan 16 '11 at 22:35
2

In the mean time, I am using this hack, by re-parsing the RDiscount output and add a rel="nofollow" to each anchor:

def markdown(input)
  html = RDiscount.new(input).to_html
  doc = Nokogiri::HTML::DocumentFragment.parse(html)
  doc.css("a").each do |link|
    link['rel'] = 'nofollow'
  end
  doc.to_html
end

Though I think this should really be handled by the markdown parser.

widgetycrank
  • 429
  • 4
  • 11
1

I needed to do something similar, add target="_new" to all links. Solved it using Kramdown and a custom Kramdown::Converter::Html class.

Define a Kramdown::Converter::Html subclass (kramdown/converter/my_html.rb in some autoload path)

class Kramdown::Converter::MyHtml < Kramdown::Converter::Html
  def convert_a(el, indent)
    el.attr['target'] = '_new'
    super
  end
end

I also have a view helper in app/helpers/application_helper.rb

def markdown(str)
  Kramdown::Converter::MyHtml.convert(Kramdown::Document.new(str).root)[0].html_safe
end

Ideally it should be possible to just use Kramdown::Document.new(str).to_my_html.html_safe but I can't get it to work in rails development mode as Kramdown uses const_defined? to see if a converter is available and that does not trigger the autoloader. Please comment if you know how to fix this.

Mattias Wadman
  • 11,172
  • 2
  • 42
  • 57
0

There is an open feature request on RDiscount to support modifying links in this fashion.

It is scheduled for one of the upcoming RDiscount 2.1.5.x releases.

David Foster
  • 6,931
  • 4
  • 41
  • 42