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

Add method #wrap to Nokogiri::XML::Element #1531

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions Manifest.txt
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ test/xml/test_document_encoding.rb
test/xml/test_document_fragment.rb
test/xml/test_dtd.rb
test/xml/test_dtd_encoding.rb
test/xml/test_element.rb
test/xml/test_element_content.rb
test/xml/test_element_decl.rb
test/xml/test_entity_decl.rb
Expand Down
12 changes: 12 additions & 0 deletions lib/nokogiri/xml/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,18 @@ def prepend_child node_or_tags
end
end


###
# Add html around this node
#
# Returns self
def wrap(html)
new_parent = document.parse(html).first
add_next_sibling(new_parent)
new_parent.add_child(self)
self
end

###
# Add +node_or_tags+ as a child of this Node.
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
Expand Down
11 changes: 3 additions & 8 deletions lib/nokogiri/xml/node_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -215,14 +215,9 @@ def inner_html *args
end

###
# Wrap this NodeSet with +html+ or the results of the builder in +blk+
def wrap(html, &blk)
each do |j|
new_parent = document.parse(html).first
j.add_next_sibling(new_parent)
new_parent.add_child(j)
end
self
# Wrap this NodeSet with +html+
def wrap html
map { |node| node.wrap html }
end

###
Expand Down
28 changes: 28 additions & 0 deletions test/xml/test_element.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
require "helper"

module Nokogiri
module XML
class TestElementContent < Nokogiri::TestCase

def test_wrap
xml = '<document>
<thing>
<div class="title">important thing</div>
</thing>
<thing>
<div class="content">stuff</div>
</thing>
<thing>
<p class="blah">more stuff</div>
</thing>
</document>'
document = Nokogiri::XML(xml)
things = document.xpath(".//thing")
things[0].wrap("<wrapper/>")
assert_equal 'wrapper', things[0].parent.name
assert_equal 'thing', document.search("//wrapper").first.children[0].name
end

end
end
end