Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix XML::Builder not handling exceptions safely - 2372 #2373

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions lib/nokogiri/xml/builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -425,15 +425,18 @@ def method_missing(method, *args, &block) # :nodoc:
def insert(node, &block)
node = @parent.add_child(node)
if block
old_parent = @parent
@parent = node
@arity ||= block.arity
if @arity <= 0
instance_eval(&block)
else
yield(self)
begin
old_parent = @parent
@parent = node
@arity ||= block.arity
if @arity <= 0
instance_eval(&block)
else
yield(self)
end
ensure
@parent = old_parent
end
@parent = old_parent
end
NodeBuilder.new(node, self)
end
Expand Down
23 changes: 23 additions & 0 deletions test/xml/test_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,29 @@ def test_builder_multiple_nodes
end
end

def test_builder_resilient_to_exceptions
builder = Nokogiri::XML::Builder.new do |xml|
xml.root do
begin
xml.a { raise "badjoras" }
rescue StandardError
# Ignored
end

xml.b
end
end

expected_output = <<~HEREDOC
<?xml version="1.0"?>
<root>
<a/>
<b/>
</root>
HEREDOC
assert_equal(expected_output, builder.to_xml)
end

def test_builder_with_utf8_text
text = "test ﺵ "
doc = Nokogiri::XML::Builder.new(encoding: "UTF-8") { |xml| xml.test(text) }.doc
Expand Down