Zero to Mojolicious: Building a Site with Zurb Foundation


Combining several of my previous posts, let's build a quick site with Mojolicious and Zurb Foundation. We will use the AssetPack plugin. Although we are serving fairly simple Javascript and CSS files now, later we can switch to using Coffeescript, Less or Sass or anything which AssetPack can pre-process.

First, install the AssetPack plugin and create a fresh "app" −

$ cpanm Mojolicious::Plugin::AssetPack
$ mojo generate app FoundationExample

Method 1 − Local copy of Foundation

Download the latest Foundation and put the files under a foundation/ directory under our "app" directory:

$ mkdir foundation
$ cd foundation
$  wget
$ unzip

Now let's create a set of relative symbolic links for each file in the Foundation directory:

$ mkdir  public/foundation/
$ ln -s -r foundation/* public/foundation/

In lib/, change the startup to −

# This method will run once at server start
sub startup {
  my $self = shift;


  my $source = "/foundation/";
  $self->asset("foundation.css" => $source."css/foundation.min.css");
  $self->asset("foundation.js" => $source."js/foundation.js");
  $self->asset("modernizr.js" => $source."js/vendor/modernizr.js");
  $self->asset("jquery.js" => $source."js/vendor/jquery.js");

  # Router
  my $r = $self->routes;

  # Normal route to controller

Continue with Both Methods, below.

Method 2 − CDN method

Use only the changes in lib/ shown above, but replace the source with −

  my $source = "" .

Continue with Both Methods, below.

Both Methods.

In lib/FoundationExample/Controller/ − change the welcome routine to:

sub welcome {
  my $self = shift;

  $self->stash(copyright_holder => 'Someone');
  $self->stash(keywords => 'something, somebody, somewhere');
  $self->stash(author => 'William Lindley');

  # Render template "example/welcome.html.ep" with message
  $self->render(msg => 'Welcome to the Mojolicious real-time web framework!');

In templates/example/welcome.html.ep − change the layout to:

% layout 'zurbish';

and templates/layouts/zurbish.html.ep −

<!DOCTYPE html>
<html lang="en">
 <meta charset="utf-8">
 <!-- Zurb Foundation stuff -->
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
%= asset 'foundation.css'
%= asset 'modernizr.js'
 <!-- end Zurb -->
 <title><%= title %></title>
 <meta name="copyright" content="Copyright ⓒ <%= ((localtime())[5]+1900) %> <%= $copyright_holder %>" />
 <meta name="keywords" content="<%= $keywords %>" />
 <meta name="author" content="<%= $author %>" />
%= asset 'jquery.js'
%= asset 'foundation.js'
<%= content %>

For more, see Jan Henning Thorsen's talk on Mojolicious::Plugin::AssetPack at MojoConf 2014.

What Happens After You Start Your Mojolicious 'app'


Please note, THIS IS A WORK IN PROGRESS, not a final article.

First let's look at the skeleton version of the main script that gets created when you execute "mojo generate app Foo" − this is foo/script/foo −

#!/usr/bin/env perl

use strict;
use warnings;

use lib 'lib';

# Start command line interface for application
require Mojolicious::Commands;

what Mojolicious::Commands does:

  • enables all the processing for Mojolicious commands like daemon, get, generate, *routes, test, *etc.

Then we do Mojolicious::Commands->start_app('Foo') which:

  • handles all the switches and arguments in the invocation command-line

  • Loads the application class (here, lib/

  • Calls the application

The source for start_app (in Mojolicious/ looks like this:

sub start_app {

This calls the new() method of Mojo::Server to create a Mojo server object (and subscribe to the "request" event with default request handling); the server object is returned and upon that we call build_app(). The argument to build_app will in this example be "Foo" which is the name of the application class for which we are building an instance.

→ Q: What does it mean, subscribe to the request event?

Then the call to start() runs as shown in, namely by invoking the commands() and run() methods of Mojolicious, which have the effect of processing any commands and then running the event loop.

The only other code, aside from a stock Controller, is in lib/

package Foo;
use Mojo::Base 'Mojolicious';

# This method will run once at server start
sub startup {
  my $self = shift;

  # Documentation browser under "/perldoc"

  # Router
  my $r = $self->routes;

  # Normal route to controller

What's going on here?

the argument is the 'app' (instance of _ class) that _ creates

From this we can call built-ins like plugin() and routes()



An event loop is basically a loop that continually tests for external events and executes the appropriate callbacks to handle them, it is often the main loop in a program. Non-blocking tests for readability/writability of file descriptors and timers are commonly used events for highly scalable network servers, because they allow a single process to handle thousands of client connections concurrently.

  1. Set up all the routes, timers, and other reactions to be processed by the event engine.

  2. The script calls app->start (for Lite) or −−− (for Mojolicious)

  3. Event loop runs − Mojo::IOLoop (detail?)


Timers, another primary feature of the event loop, are created with


"timer" in Mojo::IOLoop ]( and can for example be used to delay rendering of a response, and unlike sleep , won't block any other requests that might be processed concurrently… Recurring timers created with "recurring" in Mojo::IOLoop are slightly more powerful, but need to be stopped manually, or they would just keep getting emitted.


Since timers and other non-blocking operations are running solely in the event loop, outside of the application, exceptions that get thrown in callbacks can't get caught and handled automatically. But you can handle them manually by subscribing to the event


"error" in Mojo::Reactor ]( or catching them inside the callback.

Why I'm Excited about Mojo::Pg


Marcus Ramberg wrote in the December 2014 Perl Advent Calendar about Mojo::Pg, the new DBI wrapper for the Mojolicious framework.

Particularly of interest are

  • Automatic transaction rollback if the 'guard variable' goes out of scope. In practice this means if you just return or throw an exception in the middle of a routine, any transactions get rolled back without having to do anything yourself.

  • Migrations. Written in plain SQL and easily embedded or attached to your program, this was one of the few things I liked about Rails, but it's here now.

  • Asynchronous triggers. You could have two processes attached to the same database; when one does an INSERT, the other process gets a notification. This opens up all kinds of things that were nearly impossible before.

On top of the upcoming "INSERT … ON CONFLICT …" grammar in Postgres 9.5, which lets you do things like:

INSERT INTO distributors (did, dname)
  VALUES (5, 'Gizmo transglobal'), (6, 'Associated Computing, inc')

it's well worth considering whether to keep using MySQL at all.

Building more Simutrans tools: the Perl Imager package


In building some new tools to support Simutrans development, I found this bit of sage advice dated 2005 from Tony Cook, the developer of the Imager module. From that I revised this example to translate the "transparent" cyan that Simutrans wants in its pakfile images, to actual transparency.

Note the use of new function signatures, and hash slices.

use v5.20;
use feature 'signatures';
no warnings 'experimental::signatures';

use Imager;

sub replace_color ($img, $from_color, $to_color) {
    # Inspired by
    my $rpnexpr = <<'EOS';
x y getp1 !pix
@pix red from_red eq
@pix green from_green eq
@pix blue from_blue eq
and and
@pix alpha from_alpha eq
to_red to_green to_blue to_alpha rgba @pix ifp

    my %constants;
    # Load values via hash slices
    @constants{map {"from_$_"} qw{red green blue alpha}} = 
    @constants{map {"to_$_"  } qw{red green blue alpha}} =
        $to_color  ->rgba;
    return Imager::transform2({ rpnexpr => $rpnexpr,
                                constants => \%constants,
                                channels => 4},

my %special_colors = (
    'transparent_cyan' => [231,255,255],

my $image = Imager->new(file => $filename);
$image = $image->convert(preset => 'addalpha');
# Replace visible color with transparency
my $color = Imager::Color->new( @{$special_color{transparent_cyan}} );

# make a work image the same size as our input; add an alpha channel
my $work = Imager->new(xsize => $image->getwidth,
                       ysize => $image->getheight, channels => 4);
# fill it with the color we want transparent
$work->box(filled => 1, color => $color);

# get an image with that color replaced with transparent black
my $out = $work->difference(other => $image);

$out->write(file => 'example-output.png');

Further examples of the little Transform script language could change from more-standard "real" transparent PNGs to what Simutrans wants, or help highlight unwanted special colors that can result from anti-aliasing, or do all kinds of color or shape transforms.

Simutrans: De-mystifying the PAK format


Let's de-mystify the .pak file format. Paks are actuallyfairly simple data files, although the details can certainly be complex.

In besch/reader/, obj_reader_t::read_file() opens a file and calls read_nodes() in that same .cc to reach each node. The file begins with the version information, terminated with a Ctrl+Z (0x1A) byte:

<code class="bbc_code" style="font-size: 66%;">53 69 6d 75 74 72 61 6e  73 20 6f 62 6a 65 63 74  |Simutrans object|
20 66 69 6c 65 0a 43 6f  6d 70 69 6c 65 64 20 77  | file.Compiled w|
69 74 68 20 53 69 6d 4f  62 6a 65 63 74 73 20 30  |ith SimObjects 0|
2e 31 2e 33 65 78 70 0a  1a eb 03 00 00 52 4f 4f  |.1.3exp......ROO|
54 01 00 00 00 42 55 49  4c 26 00 25 00 08 80 03  |T....BUIL&.%....|</code>

Following that are four bytes of Pak-File version (eb 03 00 00 above), and then a series of nodes until the end of file. Each node is processed by its appropriate reader found in the besch/reader/ subdirectory. In the file, each node begins with four characters describing the node type, as defined in besch/objversion.h:

<code class="bbc_code">enum obj_type
        obj_bridge      = C4ID('B','R','D','G'),
        obj_building    = C4ID('B','U','I','L'),</code>

and then a 2-byte (16-bit) child count and 2-byte (16-bit) data block size. If the data block is more than 64k bytes, 0xFFFF is used for the data size, followed by a four-byte (32-bit) data block size. Then the actual data block bytes, followed by any additional nodes in this same format.

The child count indicates how many of the following nodes are considered to belong to (be "inside") the current node. The BUIL node in the example has 0x0026 child nodes. This is how, for example, a single pak file can contain multiple objects, with each object containing several child nodes.

Note that read_nodes() chooses the internal class type from the four-character name, using the following line of code:

<code class="bbc_code">        obj_reader_t *reader = obj_reader->get(static_cast<obj_type>(node.type));

How exactly that works, in converting a text representation to a somewhat conceptual C++ class type, is left to the student as an exercise.