Skip to content

Instantly share code, notes, and snippets.

/clone.diff Secret

Created October 23, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/058a661df4a5d9b0b598 to your computer and use it in GitHub Desktop.
Save anonymous/058a661df4a5d9b0b598 to your computer and use it in GitHub Desktop.
diff --git a/lib/Mojo/DOM.pm b/lib/Mojo/DOM.pm
index 2bda8b1..965f912 100644
--- a/lib/Mojo/DOM.pm
+++ b/lib/Mojo/DOM.pm
@@ -15,6 +15,7 @@ use Mojo::DOM::CSS;
use Mojo::DOM::HTML;
use Mojo::Util 'squish';
use Scalar::Util qw(blessed weaken);
+use Storable 'dclone';
sub all_text { shift->_all_text(1, @_) }
@@ -280,7 +281,17 @@ sub _offset {
sub _parent { $_[0]->tree->[$_[0]->type eq 'tag' ? 3 : 2] }
-sub _parse { Mojo::DOM::HTML->new(xml => shift->xml)->parse(shift)->tree }
+sub _parse {
+ my ($self, $html) = @_;
+
+ return Mojo::DOM::HTML->new(xml => $self->xml)->parse($html)->tree
+ unless blessed $html && $html->isa('Mojo::DOM');
+
+ my $clone = dclone $html->tree;
+ return $clone if $clone->[0] eq 'root';
+ _link(['root', $clone], my $parent = ['root', $clone]);
+ return $parent;
+}
sub _replace {
my ($self, $parent, $tree, $new) = @_;
diff --git a/t/mojo/dom.t b/t/mojo/dom.t
index b6c01a9..390ed75 100644
--- a/t/mojo/dom.t
+++ b/t/mojo/dom.t
@@ -462,7 +462,8 @@ $dom = Mojo::DOM->new('<div>foo<p>lalala</p>bar</div>');
is $dom->at('p')->replace('<foo>bar</foo>'), '<div>foo<foo>bar</foo>bar</div>',
'right result';
is "$dom", '<div>foo<foo>bar</foo>bar</div>', 'right result';
-$dom->at('foo')->replace(Mojo::DOM->new('text'));
+$dom->at('foo')
+ ->replace(Mojo::DOM->new('<p>text</p>')->at('p')->child_nodes->first);
is "$dom", '<div>footextbar</div>', 'right result';
$dom = Mojo::DOM->new('<div>foo</div><div>bar</div>');
$dom->find('div')->each(sub { shift->replace('<p>test</p>') });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment