Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid pretty-printing HTML in Nokogiri while using to_html?

I am using Nokogiri with Ruby on Rails v2.3.8.

Is there a way in which I can avoid pretty-printing in Nokogiri while using to_html?

I read that to_xml allows this to be done using to_xml(:indent => 0), but this doesn't work with to_html.

Right now I am using gsub to strip away new-line characters. Does Nokogiri provide any option to do it?

like image 631
Subramaniam Avatar asked Jan 22 '13 13:01

Subramaniam


1 Answers

I solved this using .to_html(save_with: 0)?

2.1.0 :001 > require 'nokogiri'
 => true
2.1.0 :002 >  doc = Nokogiri::HTML.fragment('<ul><li><span>hello</span> boom!</li></ul>')
 => #<Nokogiri::HTML::DocumentFragment:0x4e4cbd2 name="#document-fragment" children=[#<Nokogiri::XML::Element:0x4e4c97a name="ul" children=[#<Nokogiri::XML::Element:0x4e4c47a name="li" children=[#<Nokogiri::XML::Element:0x4e4c240 name="span" children=[#<Nokogiri::XML::Text:0x4e4c0a6 "hello">]>, #<Nokogiri::XML::Text:0x4e4c86c " boom!">]>]>]>
2.1.0 :003 > doc.to_html
 => "<ul><li>\n<span>hello</span> boom!</li></ul>"
2.1.0 :004 > doc.to_html(save_with: 0)
 => "<ul><li><span>hello</span> boom!</li></ul>"

tested on: nokogiri (1.6.5) + libxml2 2.7.6.dfsg-1ubuntu1 + ruby 2.1.0p0 (2013-12-25 revision 44422) [i686-linux]

like image 161
agenteo Avatar answered Oct 02 '22 09:10

agenteo