Skip to content

Commit

Permalink
added all_contents method to Mojo::DOM
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Feb 2, 2014
1 parent 4f127d8 commit 30e520a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,5 +1,6 @@

4.74 2014-02-02
- Added all_contents method to Mojo::DOM.

4.73 2014-02-01
- Improved xml_escape performance significantly.
Expand Down
17 changes: 17 additions & 0 deletions lib/Mojo/DOM.pm
Expand Up @@ -31,6 +31,8 @@ sub AUTOLOAD {

sub DESTROY { }

sub all_contents { $_[0]->_collect(_contents(_nodes($_[0]->tree))) }

sub all_text { shift->_content(1, @_) }

sub ancestors { _select($_[0]->_collect(_ancestors($_[0]->tree)), $_[1]) }
Expand Down Expand Up @@ -246,6 +248,10 @@ sub _content {
return _text([_nodes($tree)], shift, _trim($tree, @_));
}

sub _contents {
map { $_->[0] eq 'tag' ? ($_, _contents(_nodes($_))) : ($_) } @_;
}

sub _css { Mojo::DOM::CSS->new(tree => shift->tree) }

sub _delegate {
Expand Down Expand Up @@ -443,6 +449,17 @@ XML detection can also be disabled with the L</"xml"> method.
L<Mojo::DOM> implements the following methods.
=head2 all_contents
my $collection = $dom->all_contents;
Return a L<Mojo::Collection> object containing all nodes in DOM structure as
L<Mojo::DOM> and L<Mojo::DOM::Node> objects.
"<p><b>123</b></p>"
$dom->parse('<p><!-- test --><b>123<!-- 456 --></b></p>')
->all_contents->grep(sub { $_->node eq 'comment' })->remove->first;
=head2 all_text
my $trimmed = $dom->all_text;
Expand Down
11 changes: 11 additions & 0 deletions t/mojo/dom.t
Expand Up @@ -145,6 +145,17 @@ ok !$dom->at('simple')->ancestors->first->xml, 'XML mode not active';
# Nodes
$dom = Mojo::DOM->new(
'<!DOCTYPE before><p>test<![CDATA[123]]><!-- 456 --></p><?after?>');
is $dom->all_contents->[0]->node, 'doctype', 'right node';
is $dom->all_contents->[0]->content, ' before', 'right content';
is $dom->all_contents->[1]->type, 'p', 'right type';
is $dom->all_contents->[2]->node, 'text', 'right node';
is $dom->all_contents->[2]->content, 'test', 'right content';
is $dom->all_contents->[5]->node, 'pi', 'right node';
is $dom->all_contents->[5]->content, 'after', 'right content';
is $dom->at('p')->all_contents->[0]->node, 'text', 'right node';
is $dom->at('p')->all_contents->[0]->content, 'test', 'right node';
is $dom->at('p')->all_contents->[-1]->node, 'comment', 'right node';
is $dom->at('p')->all_contents->[-1]->content, ' 456 ', 'right node';
is $dom->contents->[1]->contents->first->parent->type, 'p', 'right type';
is $dom->contents->[1]->contents->first->content, 'test', 'right content';
is $dom->contents->[1]->contents->first, 'test', 'right content';
Expand Down

0 comments on commit 30e520a

Please sign in to comment.