2008-10-25 36 views
6

可以使用无效的语法编写Markdown内容。无效意味着BlueCloth库无法解析内容并引发异常。 Rails中的markdown帮助程序不捕获任何BlueCloth异常,并且因为整个页面无法呈现(而是渲染500服务器错误页面)。如何验证降价?

对我来说,允许用户编写Markdown内容并将其保存到数据库中。如果某人使用无效的语法,则该内容的所有后续呈现尝试均失败(状态码500 - 内部服务器错误)。

你如何解决这个问题?在保存到数据库之前,是否可以在模型级验证Markdown语法?

+0

你可能想知道,BlueCloth有各种问题,并有可用更好的降价库现在:http://tomayko.com/writings/ruby-markdown-libraries-real-cheap-for-you-two-for-price-of-one – 2008-10-26 09:21:19

回答

9

您应该编写自己的验证方法,在其中初始化BlueCloth对象,并尝试调用to_html方法捕获任何异常。如果发现异常,则验证失败,否则应该正常。

在你的模型:

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 
1

我已经做了一些调查,然后决定用RDiscount,而不是BlueCloth。 RDiscount似乎比BlueCloth快得多,也更可靠。

将RDiscount集成到Rails环境很容易。包括以下内容在你environment.rb剪断,你准备好了:

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

(使用Rails 2.2.0测试)