How about this? :P Time for terse overkill!
sub do_something_with_a_uri {
my $self = shift;
my $uri = shift || die "uri is required";
my $method = $self->method;
# You have to work out how to keep the JSON/Env stuff.
$self->$method($uri);
}
And here’s the full working demo code–
my @methods = qw/ get post response /; # Used by Env/GlipGlop.
package Env {
use Moo;
has "method" =>
is => "rwp",
isa => sub {
grep $_ eq $_[0], @methods
or die "No such method: $_[0]";
};
};
package GlipGlop {
use Moo;
use Scalar::Util "blessed";
has agent =>
is => "lazy",
handles => \@methods,
isa => sub {
@methods == grep $_[0]->can($_), @methods
or die "ua must be able to ", join ", ", @methods;
};
sub _build_agent {
require WWW::Mechanize;
WWW::Mechanize->new( autocheck => 0 );
}
has env =>
is => "rwp",
isa => sub { blessed $_[0] eq "Env" },
handles => [ "method" ],
default => sub {
no warnings "uninitialized";
Env->new({ method => lc $ENV{REQUEST_METHOD} || "get" });
};
sub do_something_with_a_uri {
my $self = shift;
my $uri = shift || die "uri is required";
my $method = $self->method; # "env" handles this.
# You have to work out how to keep the JSON/Env stuff.
$self->$method($uri); # the "ua" handles the @methods.
}
};
use strictures;
my $gg = GlipGlop->new;
my $uri = shift || "http://example.org";
my $response = $gg->do_something_with_a_uri($uri);
my ( $title ) = $response->content =~ m{<title[^>]*>([^<]+)}i;
print $title, $/;
__END__
moo@cow~>perl pm-1142751
Example Domain
moo@cow~>perl pm-1142751 "http://perlmonks.org/?node_id=1142751"
Better syntax for dynamic method on internal object ?