0

所以,我正在做以下事情:

sanitize(self.content, :tags => %w(""))

所以我正在采取这样的措施:

<p>one two three four five six seven eight nine then eleven</p><p>twelve thirteen</p>

并把它变成这样的东西:

one two three four five six seven eight nine then eleventwelve thirteen

如您所见,这里有一个问题:eleventwelve

我该怎么做才能在elevenand之间留一个空格twelve

4

1 回答 1

2

自定义消毒剂:) [更新]

# 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
于 2013-02-19T12:02:24.813 回答