Skip to content

Commit

Permalink
added url method to Mojo::DOM
Browse files Browse the repository at this point in the history
  • Loading branch information
jberger committed Dec 21, 2014
1 parent 398f499 commit 9293d3a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/Mojo/DOM.pm
Expand Up @@ -13,6 +13,7 @@ use Carp 'croak';
use Mojo::Collection;
use Mojo::DOM::CSS;
use Mojo::DOM::HTML;
use Mojo::URL;
use Mojo::Util qw(deprecated squish);
use Scalar::Util qw(blessed weaken);

Expand Down Expand Up @@ -184,6 +185,15 @@ sub type {
return $self;
}

sub url {
my $self = shift;
for my $attr (@_ ? @_ : qw/href src/) {
next unless my $url = $self->attr($attr);
return Mojo::URL->new($url);
}
return undef;
}

# DEPRECATED in Tiger Face!
sub val {
deprecated 'Mojo::DOM::val is DEPRECATED';
Expand Down Expand Up @@ -913,6 +923,18 @@ This element's type.
# List types of child elements
say $dom->children->map('type')->join("\n");
=head2 url
my $url = $dom->url;
my $url = $dom->url(qw/myattr href src/);
Returns a L<Mojo::URL> object for the C<href> or C<src> attribute of the node
or C<undef> if the node does not have the attributes. Optionally pass a list of
alternative attributes to search.
# "bender"
$dom->parse('<a href="/page.html#bender"></a>')->at('a')->url->fragment;
=head2 wrap
$dom = $dom->wrap('<div></div>');
Expand Down
13 changes: 13 additions & 0 deletions t/mojo/dom.t
Expand Up @@ -2393,4 +2393,17 @@ $dom = Mojo::DOM->new($huge);
is $dom->all_text, 'works', 'right text';
is "$dom", $huge, 'right result';

# url
$dom = Mojo::DOM->new('<a href="http://mojolicio.us">Mojo</a>');
my $url = $dom->at('a')->url;
isa_ok $url, 'Mojo::URL';
is $url->to_string, 'http://mojolicio.us', 'right url content';
$dom = Mojo::DOM->new('<img src="/image.png"></img>')->at('img');
is $dom->url('src')->path->parts->[-1], 'image.png', 'found src';

$dom = Mojo::DOM->new('<img src="/image.png" href="/page.html"></img>')->at('img');
is $dom->url->path->parts->[-1], 'page.html', 'found href';
is $dom->url('src')->path->parts->[-1], 'image.png', 'found src';
is $dom->url('myattr'), undef, 'attribute not found';

done_testing();

1 comment on commit 9293d3a

@s1037989
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Please sign in to comment.