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?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With