2010-01-11 61 views

回答

8

我在使用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 
+0

謝謝,這看起來像一個很好的方法來解決這個問題。我會試一試。 – 2010-01-12 04:03:20