From e7b641bd51582124737ceff3d7032c4570cdcbb9 Mon Sep 17 00:00:00 2001 From: ellaklara Date: Mon, 27 Feb 2023 11:06:06 +0100 Subject: [PATCH] fix: support Encoding class for write_to --- lib/nokogiri/xml/node.rb | 2 ++ test/xml/test_node.rb | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/nokogiri/xml/node.rb b/lib/nokogiri/xml/node.rb index d591ce77203..3dc97b4d8bb 100644 --- a/lib/nokogiri/xml/node.rb +++ b/lib/nokogiri/xml/node.rb @@ -1365,6 +1365,8 @@ def write_to(io, *options) config = SaveOptions.new(save_options.to_i) yield config if block_given? + encoding = encoding.is_a?(Encoding) ? encoding.name : encoding + native_write_to(io, encoding, indentation, config.options) end diff --git a/test/xml/test_node.rb b/test/xml/test_node.rb index 040c93aece9..9ed6627512c 100644 --- a/test/xml/test_node.rb +++ b/test/xml/test_node.rb @@ -9,6 +9,7 @@ module XML class TestNode < Nokogiri::TestCase describe Nokogiri::XML::Node do let(:xml) { Nokogiri::XML(File.read(XML_FILE), XML_FILE) } + let(:xml_UTF_8) { Nokogiri::XML(File.read(XML_ATOM_FILE), XML_ATOM_FILE) } def test_first_element_child node = xml.root.first_element_child @@ -679,6 +680,22 @@ def test_write_to_with_block end end + def test_write_to_file_with_encoding_string + Tempfile.create do |io| + xml_UTF_8.write_to(io, encoding: "UTF-8") + io.rewind + assert_equal(xml_UTF_8.to_xml, io.read) + end + end + + def test_write_to_file_with_encoding_class + Tempfile.create do |io| + xml_UTF_8.write_to(io, encoding: Encoding::UTF_8) + io.rewind + assert_equal(xml_UTF_8.to_xml, io.read) + end + end + def test_write_to_file_without_encoding Tempfile.create do |io| xml.write_to(io)