In the previous examples using Bailador we put all the code in a single app.pl file. At one point we moved the HTML template to the views/ subdirectory, but for larger applications and for reusable code, we'll want to be able to put code in separate files. That's what we are going to do now.
The template does not have anything new. It accepts data in the $h variable and then uses that variable to display the version number and the current time - in seconds since the epoch.
bailador/code_in_module/views/index.tt
% my ($h) = @_; <!DOCTYPE html> <html> <head> <title>Bailador App</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> </head> <body> <h1>Bailador App</h1> <div> Version <%= $h<version> %> Current time: <%= $h<date> %> </div> </body> </html>
The file contains all the code in a class:
unit class Demo;
It loads Bailador in order to have the Domain Specific Language (DSL) that makes it easy for us to define the routes.
use Bailador;
Most importantly, it contains the routes.
bailador/code_in_module/lib/Demo.pm
unit class Demo; use Bailador; my $version = '0.01'; get '/' => sub { template 'index.tt', { version => $version, date => time } }
bailador/code_in_module/app.pl
use Bailador; Bailador::import(); use lib callframe(0).file.IO.dirname ~ '/lib'; use Demo; baile;
The part that might be interesting is this snippet:
use lib callframe(0).file.IO.dirname ~ '/lib';
It calculates the root directory of the project - assuming the app.pl file is in root directory - and then adds the /lib subdirectory to the list of places where perl is going to look for extra modules. This makes it possible for it to load the Demo.pm file that can be found in the lib/ subdirectory.
Published on 2015-08-01