使用无效语法编写 Markdown 内容是可能的。无效意味着 BlueCloth 库无法解析内容并引发异常。 Rails中的 markdown 帮助程序不会捕获任何BlueCloth异常,因此完整页面无法呈现(而是呈现500 Server Error页面)。

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

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

有帮助吗?

解决方案

您应该编写自己的验证方法,在其中初始化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

其他提示

我做了一些研究并决定使用 RDiscount 而不是BlueCloth。 RDiscount似乎比BlueCloth更快,更可靠。

在您的Rails环境中集成RDiscount很容易。在 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测试)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top