2009-06-05 143 views
2

有誰知道我可以如何將html轉換爲純文本。那麼我真的需要將RedCloth轉換爲純文本,無論哪種方式都可以。Ruby:將HTML/Redcloth轉換爲純文本

我不是在談論剝離標籤(這是我迄今爲止所做的所有)。例如,我想一個有序列表來保留號碼,無序列表使用的子彈等星號

def red_cloth_to_plain_text(s) 
     s = RedCloth.new(s).to_html 
     s = strip_tags(s) 
     s = html_unescape(s) # reverse of html_escape 
     s = undo_red_cloths_html_codes(s) 
     return s 
end 

也許我不得不嘗試RedCloth以純文本格式

回答

2

您需要製作一個新的格式器類。

module RedCloth::Formatters 
    module PlainText 
    include RedCloth::Formatters::Base 
    # ... 
    end 
end 

我今天不會爲你寫代碼,但這很容易做到。如果您懷疑我,請閱讀RedCloth源代碼:HTML格式化程序只有346行。

所以,一旦你有你的純文本格式,你修補類,並使用它:

module RedCloth 
    class TextileDoc 
    def to_txt(*rules) 
     apply_rules(rules) 
     to(RedCloth::Formatters::PlainText) 
    end 
    end 
end 

print RedCloth.new(str).to_txt