How to check the marking?

It is possible to write Markdown content with invalid syntax. Invalid means that the BlueCloth library cannot parse the contents and throws an exception. The markdown in Rails does not catch any BlueCloth exceptions, and because of this, the full page is not displayed (the "Server 500 Error" page is displayed instead).

In my case, users are allowed to write Markdown content and save it in the database. If someone used an invalid syntax, all subsequent attempts to render this content will fail (Status Code 500 - Internal Server Error).

How did you get around this problem? Is it possible to check the Markdown syntax at the model level before saving to the database?

+6
ruby ruby-on-rails markdown
source share
2 answers

You must write your own validation method in which you must initialize the BlueCloth object, and try calling the to_html method, which will catch any exception. If you catch the exception, the check failed, otherwise it should be fine.

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 
+9
source share

I did a bit of work and decided to use RDiscount instead of BlueCloth. RDiscount seems much faster and more reliable than BlueCloth.

Easily integrate RDiscount into your Rails environment. Add the following snapshot to 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)

+1
source share

All Articles