カスタムサニタイザー:)[更新]
# 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"}}
あなたの例:
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"
複数の条件の例:
custom_sanitize(html, {:tag => "p"}, {:tag => "div", :attributes => {:class => "title"})
=========
モデルの場合[シンプルバージョン]
ヘルパーファイルにヘルパーを含めると、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