使用Nokogiri将标记替换为<%= image_tag%>?

| 如何使用nokogiri将所有img标签替换为图片标签?这是利用Rails的能力自动插入正确的资产服务器吗?
require \'nokogiri\'

class ToImageTag

  def self.convert
    Dir.glob(\"app/views/**/*\").each do |filename|
      doc = Nokogiri::HTML(File.open(filename))
      doc.xpath(\"//img\").each |img_tags|
        # grab the src and all the attributes and move them to ERB
      end

    # rewrite the file
    end

  rescue => err
    puts \"Exception: #{err}\"
  end

end
    
已邀请:
        受maerics的响应启发,我创建了一个脚本来执行此操作。 HTML实体没有问题,因为它仅使用nokogiri输出作为替换指南。实际的替换是通过使用String#gsub完成的! https://gist.github.com/1254319     
        我能想到的最接近的如下:
# ......
Dir.glob(\"app/views/**/*\").each do |filename|
  # Convert each \"img\" tag into a text node.
  doc = Nokogiri::HTML(File.open(filename))
  doc.xpath(\"//img\").each do |img|
    image_tag = \"<%= image_tag(\'#{img[\'src\']}\') %>\"
    img.replace(doc.create_text_node(image_tag))
  end
  # Replace the new text nodes with ERB markup.
  s = doc.to_s.gsub(/(&lt;%|%&gt;)/) {|x| x==\'&lt;%\' ? \'<%\' : \'%>\'}
  File.open(filename, \"w\") {|f| f.write(s)}
end
该解决方案将对包含序列“
&lt%
\”或“
%&gt;
\”的任何文件造成严重破坏(例如,如果您使用HTML描述ERB语法)。问题是您正在尝试使用XML解析器将XML节点替换为必须转义的文本,因此,我不确定您可以做得更好,除非存在一些隐藏的“ 4”。 “ 方法。 最好的总体选择是编写一个自定义的SAX解析器,该解析器将仅回显提供给回调的数据(或将其存储在字符串缓冲区中),除非它是带有\“ img \”的\“ start_element \”,在这种情况下,它将写入ERB序列。     

要回复问题请先登录注册