Can I create an object in Dancer to return a value for display?

I have the following code in my Dancer application module:

package Deadlands; use Dancer ':syntax'; use Dice; our $VERSION = '0.1'; get '/' => sub { my ($dieQty, $dieType); $dieQty = param('dieQty'); $dieType = param('dieType'); if (defined $dieQty && defined $dieType) { return Dice->new(dieType => $dieType, dieQty => $dieQty)->getStandardResult(); } template 'index'; }; true; 

I have a Moops class called Dice.pm that works fine if I test it with a .pl file, but when I try to access it through a web browser, I get the following error: Can not find the object method "new "via the" Dice "package (maybe you forgot to download" Dice "?) .

Can I do it with Dancer?

Here is the relevant code from Dice.pm:

 use 5.14.3; use Moops; class Dice 1.0 { has dieType => (is => 'rw', isa => Int, required => 1); has dieQty => (is => 'rw', isa => Int, required => 1); has finalResult => (is => 'rw', isa => Int, required => 0); method getStandardResult() { $self->finalResult(int(rand($self->dieType()) + 1)); return $self->finalResult(); } } 
+6
source share
1 answer

I was going to say that you forgot package Dice in your Dice.pm , but after reading on Moops I got confused in namespaces.

Take a look at the documentation for Moops .

If you use Moops inside a package other than the main one, the package names used in the declaration are "qualified" by this external package if they do not contain "::". For example:

 package Quux; use Moops; class Foo { } # declares Quux::Foo class Xyzzy::Foo # declares Xyzzy::Foo extends Foo { } # ... extending Quux::Foo class ::Baz { } # declares Baz 

If class Dice is in Dice.pm , it really will become Dice::Dice if I read it correctly. So you would have to use Dice and create your object using Dice::Dice->new .

To make a Dice package inside Dice.pm using Moops, I believe you need to declare a class like this:

 class ::Dice 1.0 { # ^------------- there are two colons here! has dieType => (is => 'rw', isa => Int, required => 1); has dieQty => (is => 'rw', isa => Int, required => 1); has finalResult => (is => 'rw', isa => Int, required => 0); method getStandardResult() { $self->finalResult(int(rand($self->dieType()) + 1)); return $self->finalResult(); } } 

Then you can:

 use Dice; Dice->new; 
+3
source

All Articles