如何在Ruby中限制Markdown语法?

我希望使用诸如Maraku或Kramdown之类的Ruby库在Rails CMS评论系统中实现Markdown。 我需要限制用户可以提交的Markdownfunction。 在此系统中,不允许用户插入图像,html或执行任何繁重的编辑,但强调和超链接是可以的。

基本上,我希望创建类似于这个Textilefilter的东西,但是对于Markdown语法。

在markdown trasformation之后我一直在使用sanitize gem来清理数据。 它基于白名单,非常易于配置,您可以轻松实现您的目标。

为了节省你一些时间,这是我的文本格式化模块,希望它可以帮助你。 内置的宽松规则对我来说有点过于严格。

module TextFormatter require 'sanitize' module Formatters MARKDOWN = 1 TEXTILE = 2 end RELAXED = { :elements => [ 'a', 'b', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'dl', 'dt', 'em', 'i', 'img', 'li', 'ol', 'p', 'pre', 'q', 'small', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'u', 'ul', 'del', 'ins', 'h1', 'h2', 'h3', 'h4', 'h5', 'h5', 'hr', 'kbd'], :attributes => { 'a' => ['href', 'title'], 'blockquote' => ['cite'], 'col' => ['span', 'width'], 'colgroup' => ['span', 'width'], 'img' => ['align', 'alt', 'height', 'src', 'title', 'width'], 'ol' => ['start', 'type'], 'q' => ['cite'], 'table' => ['summary', 'width'], 'td' => ['abbr', 'axis', 'colspan', 'rowspan', 'width'], 'th' => ['abbr', 'axis', 'colspan', 'rowspan', 'scope', 'width'], 'ul' => ['type'] }, :protocols => { 'a' => {'href' => ['ftp', 'http', 'https', 'mailto', :relative]}, 'blockquote' => {'cite' => ['http', 'https', :relative]}, 'img' => {'src' => ['http', 'https', :relative]}, 'q' => {'cite' => ['http', 'https', :relative]} } } def self.to_html(text, formatter = Formatters::MARKDOWN) return "" unless text html = case formatter when Formatters::MARKDOWN then RDiscount.new(text, :smart).to_html when Formatters::TEXTILE then RedCloth.new(text).to_html end Sanitize.clean(html, RELAXED) end end