[Dancer-users] separating code into packages

Gabor Szabo szabgab at gmail.com
Sat Dec 25 10:01:22 CET 2010


On Fri, Dec 24, 2010 at 5:32 PM, Puneet Kishor <punk.kish at gmail.com> wrote:
>
>
> Gabor Szabo wrote:
>>
>> I have not reached that point yet but as your application grows it
>> might be better
>> to move some code and with that some route definition to separate files.
>> For example if I have a Dancer application called Foo I might
>> want to move all the user related methods
>>
>> get '/user/this' =>  sub { ... };
>> get '/user/that' =>  sub { ... };
>> get '/user/other' =>  sub { ... };
>>
>> to a package called Foo::User;
>>
>> I can then include
>>
>> use Foo::User;
>>
>> in the main Foo package and the above routes are added.
>>
>> Within Foo::User the /user prefix seems to be too repetitive so
>> it might be better to have just
>>
>> get '/this' =>  sub { ... };
>> get '/that' =>  sub { ... };
>> get '/other' =>  sub { ... };
>>
>> and mount that package to '/user' within the Foo application.
>> (which by itself might have been mounted to some path.
>>
>
> Have you looked at `load_app`?
>
>        package Foo.pm
>        use Dancer ":syntax";
>
>        load_app "Foo::User", prefix => "/user";
>

I tried that but that overrides any previous setting of 'prefix'.
So if I mounted Foo to lets say '/foo'  I'd like /user to become
/foo/user
The example you gave works but it mounts /user to the root directory.

Presumably what I should do is fetch the current prefix and append
the additional prefixes to that so I'd need to do is something like this:

my $prefix = prefix();
load_app "Foo::User", prefix => "$prefix/user";

unfortunately prefix() in that case will reset the current prefix and
always returns 1.
Even though the docs says you need to call   prefix undef;   for that
which is IMHO
a bit misleading.

Reading the set_prefix method in Dancer::App it is unclear to me what
is the gain in always returning 1.

Maybe the prefix() function could be changes to always return the previous value
or there could be a separate method get_prefix, that would return the
current prefix.

In the end I found some other way. I am not sure if it is blessed by
the Dancer developers or not:

my $prefix = Dancer::App->current->prefix();
load_app "Foo::User", prefix => "$prefix/user";
Dancer::App->current->prefix($prefix);

Gabor


More information about the Dancer-users mailing list