Router-Dumb
view release on metacpan or search on metacpan
lib/Router/Dumb/Helper/FileMapper.pm view on Meta::CPAN
#pod =attr target_munger
#pod
#pod This attribute (which has a default no-op value) must be a coderef. It is
#pod called like a method, with the first non-self argument being the file
#pod responsible for the route. It should return the target for the route to be
#pod added.
#pod
#pod =cut
has target_munger => (
reader => '_target_munger',
isa => 'CodeRef',
default => sub { sub { $_[1] } },
);
#pod =attr parts_munger
#pod
#pod This attribute (which has a default no-op value) must be a coderef. It is
#pod called like a method, with the first non-self argument being an arrayref of the
#pod path components of the file responsible for the route. It should return the
#pod parts for the route to be added.
#pod
#pod =cut
has parts_munger => (
reader => '_parts_munger',
isa => 'CodeRef',
default => sub { sub { $_[1] } },
);
#pod =method add_routes_to
#pod
#pod $helper->add_routes_to( $router, \%arg );
#pod
#pod This message tells the helper to scan its directory root and add routes to the
#pod given router. The helper can be used over and over.
#pod
#pod Valid arguments are:
#pod
#pod ignore_conflicts - if true, trying adding an existing route will be ignored,
#pod rather than fail
#pod
#pod =cut
sub add_routes_to {
my ($self, $router, $arg) = @_;
$arg ||= {};
my $dir = $self->root;
my @files = File::Find::Rule->file->in($dir);
my $add_method = $arg->{ignore_conflicts}
? 'add_route_unless_exists'
: 'add_route';
for my $file (@files) {
my $path = $file =~ s{/INDEX$}{/}gr;
$path =~ s{$dir}{};
$path =~ s{^/}{};
my @parts = split m{/}, $path;
confess "can't use placeholder-like name in route files"
if grep {; /^:/ } @parts;
confess "can't use asterisk in file names" if grep {; $_ eq '*' } @parts;
my $route = Router::Dumb::Route->new({
parts => $self->_parts_munger->( $self, \@parts ),
target => $self->_target_munger->( $self, $file ),
});
$router->$add_method($route);
}
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Router::Dumb::Helper::FileMapper - something to build routes out of a dumb tree of files
=head1 VERSION
version 0.006
=head1 OVERVIEW
The FileMapper helper looks over a tree of files and adds routes to a
L<Router::Dumb> object based on those files.
For example, imagine the following file hierarchy:
templates
templates/pages
templates/pages/help
templates/pages/images
templates/pages/images/INDEX
templates/pages/INDEX
templates/pages/legal
templates/pages/legal/privacy
templates/pages/legal/tos
With the following code...
use Path::Class qw(dir);
my $r = Router::Dumb->new;
Router::Dumb::Helper::FileMapper->new({
root => 'templates/pages',
target_munger => sub {
my ($self, $filename) = @_;
dir('pages')->file( file($filename)->relative($self->root) )
->stringify;
( run in 0.736 second using v1.01-cache-2.11-cpan-71847e10f99 )