I wrote the Sledge::Plugin::URIFor.This module provides $self->uri_for() method
$self->uri_for('Proj::Pages::Foo' => 'add', {id => 35}); # => /foo/add?id=35
package Sledge::Plugin::URIFor; use strict; use warnings; our $VERSION = 0.01; use Carp; use Sledge::Utils; use URI;
sub import { my $pkg = caller(0);
no strict 'refs'; *{"$pkg\::uri_for"} = sub { my $self = shift;
my @args = @_;
my $dir = Sledge::Utils::class2prefix($self); my $page = ''; my $query = {};
for my $arg (@args) { if (ref $arg eq 'HASH') { # query $query = $arg; } elsif ($arg =~ /^[A-Z]/) { # module name my $appclass = Sledge::Utils::class2appclass($self); $arg = "${appclass}::Pages::$arg" unless $arg =~ /^$appclass/;
$dir = Sledge::Utils::class2prefix($arg); } elsif ($arg =~ /^[a-z]/) { # page name next if $arg eq 'index'; # through $page = $arg; } else { die "invalid argument : $arg"; } }
my $uri = URI->new($dir .($dir eq '/' ? '' : '/'). $page); $uri->query_form($query);
return $uri->as_string; }; }
1;
use strict; use warnings; use Test::Base;
plan tests => 1*blocks;
filters( { input => [qw/yaml/], } );
run { my $block = shift;
eval qq{ package @{[ $block->pages ]}; use Sledge::Plugin::URIFor; sub new { bless {}, shift } }; die $@ if $@;
my $page = $block->pages->new; is( $page->uri_for( @{ $block->input } ), $block->expected, $block->name ); };
__END__
=== simple --- pages: Proj::Pages --- input - foo: bar --- expected: /?foo=bar
=== deep --- pages: Proj::Pages::Foo --- input - add --- expected: /foo/add
=== complex --- pages: Proj::Pages::Foo::Bar --- input - Bar::Baz - edit - foo: bar bar: baz --- expected: /bar/baz/edit?bar=baz&foo=bar
=== complex2 --- pages: Proj::Pages::Foo::Bar::Baz --- input - Proj::Pages::Bar::Baz - edit - foo: bar bar: baz --- expected: /bar/baz/edit?bar=baz&foo=bar