From f13cdb46406c9b119a368cf506d831865dd95163 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Tue, 7 Feb 2023 10:48:01 -0500 Subject: [PATCH] fix: empty node set serialization when document encoding is nil Fixes #2784 (backport) --- lib/nokogiri/xml/node_set.rb | 5 +++-- test/xml/test_node_set.rb | 6 ++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/nokogiri/xml/node_set.rb b/lib/nokogiri/xml/node_set.rb index f5f2015c2a..8d31ea5b9a 100644 --- a/lib/nokogiri/xml/node_set.rb +++ b/lib/nokogiri/xml/node_set.rb @@ -345,8 +345,9 @@ def to_html(*args) args.insert(0, options) end if empty? - encoding = (args.first.is_a?(Hash) ? args.first[:encoding] : nil) || document.encoding - "".encode(encoding) + encoding = (args.first.is_a?(Hash) ? args.first[:encoding] : nil) + encoding ||= document.encoding + encoding.nil? ? "" : "".encode(encoding) else map { |x| x.to_html(*args) }.join end diff --git a/test/xml/test_node_set.rb b/test/xml/test_node_set.rb index fb81d6ffbe..18fb2b8b90 100644 --- a/test/xml/test_node_set.rb +++ b/test/xml/test_node_set.rb @@ -961,6 +961,12 @@ def awesome!; end assert_equal(doc2, node_set[1].document) end end + + describe "empty sets" do + it "#to_html returns an empty string" do + assert_equal("", NodeSet.new(xml, []).to_html) + end + end end end end