Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate Markdown?

It's possible to write Markdown content with invalid syntax. Invalid means that the BlueCloth library fails to parse the content and throws an exception. The markdown helper in Rails doesn't catch any BlueCloth exceptions and because of that the complete page fails to render (500 Server Error page is rendered instead).

In my case, users are allowed to write Markdown content and save it to the database. If someone used invalid syntax, all successive rendering attempts of that content fail (Status Code 500 - Internal Server Error).

How do you get around this issue? Is it possible to validate the Markdown syntax at the Model-level before saving to the database?

like image 771
Christoph Schiessl Avatar asked Oct 25 '08 22:10

Christoph Schiessl


2 Answers

You should write your own validation method in which you would initialize BlueCloth object, and try to call to_html method catching any exception. If you catch an exception, validation fails, otherwise it should be ok.

In your model:

protected:

def validate
  bc = BlueCloth.new(your_markdown_string_attribute)
  begin
    bc.to_html
  rescue
    errors.add(:your_markdown_string_attribute, 'has invalid markdown syntax')
  end
end
like image 145
Damir Zekić Avatar answered Nov 14 '22 10:11

Damir Zekić


I've done a bit of research and decided to use RDiscount instead of BlueCloth. RDiscount seems to be much faster and more reliable than BlueCloth.

It's easy to integrate RDiscount in your Rails environment. Include the following snipped in your environment.rb and you are ready to go:

begin
  require "rdiscount"
  BlueCloth = RDiscount
rescue LoadError
  # BlueCloth is still the our fallback,
  # if RDiscount is not available
  require 'bluecloth'
end

(tested with Rails 2.2.0)

like image 1
Christoph Schiessl Avatar answered Nov 14 '22 09:11

Christoph Schiessl