Ruby on rails 如何制作;“消毒”;Rails方法在HTML原来所在的位置留下一个空间?

Ruby on rails 如何制作;“消毒”;Rails方法在HTML原来所在的位置留下一个空间?,ruby-on-rails,Ruby On Rails,因此,我正在做以下工作: sanitize(self.content, :tags => %w("")) 所以我采取了这样的措施: 一二三四五六七八九然后十一一二十三 把它变成这样: 一二三四五六七八九然后一二三 正如您所看到的,这里有一个问题:eleven十二 我该怎么做才能在11和12之间留出空间?定制消毒剂:)[更新] # models/custom_sanitizer.rb class CustomSanitizer def do(html, *conditions)

因此,我正在做以下工作:

sanitize(self.content, :tags => %w(""))
所以我采取了这样的措施:

一二三四五六七八九然后十一

一二十三

把它变成这样:

一二三四五六七八九然后一二三

正如您所看到的,这里有一个问题:
eleven十二

我该怎么做才能在
11
12
之间留出空间?

定制消毒剂:)[更新]

# 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
你的例子是:

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"
=========

适用于[简单版]

将helper包含到helper文件中,您只需为ActionView环境打开它。如果您想在AR模型中使用此方法,应该在加载Rails之前将其包含到ActiveRecord::Base中。但直接使用CustomSanitarizer类非常容易:

class Post < ActiveRecord::Base

  def no_html_content
    CustomSanitizer.new.do(content, :tag => "p")
  end

end

# Post.find(1).no_html_content
class Post“p”)
结束
结束
#Post.find(1).没有html内容

非常感谢!对不起,我不熟悉这种代码。这应该放在哪个文件中以及如何使用?将类代码放在
models/sanitizer.rb
中,并将助手代码放在任何助手文件中。噢,谢谢!但是,等等,它是否覆盖了Rails的默认
sanitize
?我刚刚改进了代码,以适应html内容包含多个嵌套标记的情况,如
一个两个

。以前的代码将在“2”之前插入3个空格。现在没事了,只剩一个空间了。非常感谢!最后一个问题,我把上面所有的代码放在
models/sanitizer.rb
中,然后在
models/post.rb
中,我创建了一个方法并添加了这个
custom\u sanitize(self.content,:tags=>%w(“p”)
但是我得到了这个未定义的方法
custom\u sanitize',我想我做得不对。
custom_sanitize(html, {:tag => "p"}, {:tag => "div", :attributes => {:class => "title"})
class Post < ActiveRecord::Base

  def no_html_content
    CustomSanitizer.new.do(content, :tag => "p")
  end

end

# Post.find(1).no_html_content