定製消毒劑:) [更新]
# models/custom_sanitizer.rb
class CustomSanitizer
def do(html, *conditions)
document = HTML::Document.new(html)
export = ActiveSupport::SafeBuffer.new # or just String
parse(document.root) do |node|
if node.is_a?(HTML::Text)
if node.parent.is_a?(HTML::Tag) && match(node.parent, conditions) && export.present?
export << " "
end
export << node.to_s
end
end
export
end
private
def match(node, conditions = [])
eval(conditions.map {|c| "node.match(#{c})"}.join(" || "))
end
def parse(node, &block)
node.children.each do |node|
yield node if block_given?
if node.is_a?(HTML::Tag)
parse(node, &block)
end
end
end
end
# Helper
def custom_sanitize(*args)
CustomSanitizer.new.do(*args)
end
基本用法:
custom_sanitize(html, conditions)
# where conditions is a hash or hashes like {:tag => "p", :attributes => {:class => "new_line"}}
你例如:
custom_sanitize(html, {:tag => "p"}, {:tag => "div", :attributes => {:class => "title"})
:
html = "<p>one two three four five six seven eight nine then eleven</p><p>twelve thirteen</p>"
custom_sanitize(html, :tag => "p")
#=> "one two three four five six seven eight nine then eleven twelve thirteen"
的多個條件實施例
=========
對於模型[簡版]
包括幫助到幫助文件你打開它對於環境的ActionView。如果你想在AR模型中使用這個方法,你應該在加載Rails之前將它包含在ActiveRecord :: Base中。但很容易直接使用CustomSanitizer類:
class Post < ActiveRecord::Base
def no_html_content
CustomSanitizer.new.do(content, :tag => "p")
end
end
# Post.find(1).no_html_content
非常感謝!對不起,我不熟悉這種代碼。應該在哪個文件中以及如何使用它? – alexchenco 2013-02-19 12:33:48
將類代碼放入'models/sanitizer.rb'中,並將輔助代碼放入任何助手文件中。 – 2013-02-19 12:41:23
噢,謝謝!但是,等一下,它覆蓋Rails的默認'清理'? – alexchenco 2013-02-19 13:02:32