Skip to content

Commit 3446a3f

Browse files
committed
Simplify args parsing
1 parent 70a8d8f commit 3446a3f

File tree

2 files changed

+20
-26
lines changed

2 files changed

+20
-26
lines changed

lib/XML/Feed.pm

Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -25,39 +25,33 @@ sub new {
2525
my $format = shift // 'Atom';
2626

2727
# Handle optional args hash
28-
my %args;
28+
my $args = {};
29+
my @valid_args = qw[useragent];
30+
2931
if (@_ && ref($_[-1]) eq 'HASH') {
30-
my $potential_args = $_[-1];
31-
# Check if this looks like our args hash (has known keys)
32-
my @known_keys = qw(useragent);
33-
my @hash_keys = keys %$potential_args;
34-
35-
# If any key matches our known args, treat it as args hash
36-
if (grep { my $k = $_; grep { $k eq $_ } @known_keys } @hash_keys) {
37-
%args = %{pop @_};
38-
39-
# Validate useragent parameter if provided
40-
if (exists $args{useragent}) {
41-
unless (blessed($args{useragent}) && $args{useragent}->isa('LWP::UserAgent')) {
42-
Carp::croak("useragent must be an LWP::UserAgent object");
43-
}
44-
}
45-
46-
# Only known keys are allowed
47-
my @invalid_keys = grep { my $k = $_; !grep { $k eq $_ } @known_keys } keys %args;
48-
if (@invalid_keys) {
49-
Carp::croak("Invalid argument(s): " . join(', ', @invalid_keys));
32+
my $possible_args = pop @_;
33+
34+
for (@valid_args) {
35+
$args->{$_} = delete $possible_args->{$_}
36+
if exists $possible_args->{$_};
37+
}
38+
39+
unless (keys %$args) {
40+
Carp::croak('No valid keys passed to ' . __PACKAGE__ . 'new()');
41+
}
42+
43+
# Validate useragent parameter if provided
44+
if (exists $args->{useragent}) {
45+
unless (blessed($args->{useragent}) && $args->{useragent}->isa('LWP::UserAgent')) {
46+
Carp::croak("useragent must be an LWP::UserAgent object");
5047
}
5148
}
5249
}
5350

5451
my $format_class = 'XML::Feed::Format::' . $format;
5552
eval "use $format_class";
5653
Carp::croak("Unsupported format $format: $@") if $@;
57-
my $feed = bless {}, join('::', __PACKAGE__, "Format", $format);
58-
59-
# Store useragent if provided
60-
$feed->{useragent} = $args{useragent} if exists $args{useragent};
54+
my $feed = bless $args, join('::', __PACKAGE__, "Format", $format);
6155

6256
$feed->init_empty(@_) or return $class->error($feed->errstr);
6357
$feed;

t/31-useragent.t

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ use LWP::UserAgent;
3535
eval {
3636
my $feed = XML::Feed->new('Atom', { invalid_arg => 'value' });
3737
};
38-
like($@, qr/Invalid argument/, 'Dies with invalid argument');
38+
like($@, qr/No valid keys passed to/, 'Dies with invalid argument');
3939
}
4040

4141
# Test 5: useragent() getter creates one if it doesn't exist

0 commit comments

Comments
 (0)