15. package MyClass;
use Mojo::Base -base;
has some_attr => '';
package main;
my $instance = MyClass->new(%hash);
my $instance = MyClass->new($hash_ref);
say $instance->some_attr; # ''
$instance->some_attr('a');
say $instance->some_attr; # 'a'
16. package MyClass; hasと同じ
use Mojo::Base -base;
__PACKAGE__->attr(some_attr => '');
package main;
my $instance = MyClass->new(%hash);
my $instance = MyClass->new($hash_ref);
say $instance->some_attr; # ''
$instance->some_attr('a');
say $instance->some_attr; # 'a'
17. ※注) 初期値はスカラーのみ
has 'name';
has name => 'foo';
has name => sub {...};
※注) コードリファレンスが
初期値になる訳ではない
30. index.htmlを補完するのに
around_dispatchフックを用いる
#!/usr/bin/env perl
use Mojolicious::Lite;
app->hook(around_dispatch => sub {
my ($next, $c) = @_;
## pre process
$next->();
## post process
});
app->start;
31. リクエストパスを補完するのに
around_dispatchフックを用いる
app->hook(around_dispatch => sub {
my ($next, $c) = @_;
## pre process
$next->();
## post process
});
Plack::Middlewareに似てる
32. index.htmlを補完する
app->hook(around_dispatch => sub {
my ($next, $c) = @_;
# auto fill file name
my $path = $c->req->url->path;
if ($path->trailing_slash || ! @{$path->parts}) {
push(@{$path->parts}, 'index.html');
$path->trailing_slash(0);
}
$next->();
## post process
});
app->start;
35. パスをディレクトリ階層に変換するルート
get '/' => 'index';
get '/index.html' => 'index';
get '/index2.html' => 'index2';
get '/dir/' => 'dir/index';
get '/dir/index.html' => 'dir/index';
get '/dir/index2.html' => 'dir/index2';
36. パスをディレクトリ階層に変換するルート
# /path/to/index.html
# stash => {
template => '/path/to/index',
format => 'html'
}
get '(*template).(*format)' => sub {
my $c = shift;
$c->render;
$c->res->code || $c->render_not_found;
};
37. /index.html.epへのリクエストを403に
app->hook(around_dispatch => sub {
my ($next, $c) = @_;
if ($c->req->url->path =~ qr{.ep$}) {
$c->render_exception('Forbidden');
$c->res->code(403);
return;
}
# auto fill file name
my $path = $c->req->url->path;
if ($path->trailing_slash || ! @{$path->parts}) {
push(@{$path->parts}, 'index.html');
$path->trailing_slash(0);
}
$next->();
});