2011-06-15 153 views
2

如何使用nokogiri替换所有带图像标签的img标签?这是为了利用Rails自动插入正确资产服务器的能力?使用Nokogiri用<%= image_tag%>替换<img src />标签?

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 
+0

也许你可以用一个例子来澄清你想要做什么,为什么? 是您想要更改资产服务器,并添加缓存清除时间戳吗? – 2011-06-15 19:28:21

回答

1

有点受到maerics'响应的启发,我创建了一个脚本来做到这一点。它对HTML实体没有任何问题,因为它仅使用nokogiri输出作为替换指南。实际的替换是通过使用String#gsub完成的!

https://gist.github.com/1254319

4

我可以想出最接近的是如下:

# ...... 
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节点,所以我不确定你可以做得比这更好,除非有一些隐藏的“raw_outer_xml=(str)”方法。

你最好总体打赌是编写一个自定义的SAX解析器,它只是回应给你回调的数据(或将它存储在字符串缓冲区中),除非它是带有“img”的“start_element”,其中它会写入ERB序列。

+1

看来nokogiri无法解析ERB,所以我将不得不使用正则表达式。 – maletor 2011-06-16 23:09:09

+0

Nokogiri不是ERB解析器。 ERB文档可以包含HTML标签,但这些标签也可以是XML或用于批量邮寄活动的文字处理模板。 – 2011-06-19 08:16:00

+1

对,我正在考虑在纯HTML文档中将一些标签转换为ERB,但ERB文档则是另一回事。 ERB是否公开其解析器? – maerics 2011-06-19 15:50:48