about sitehisaichi5518がPerlを書いて、つついて、イチャイチャするブログ。最近はnode.jsもやってる。

hisaichi5518プロフィール/ twitter管理人twitter/ rss feedRSS feed

今、Maltsを見なおしてる。get ‘/’ => sub {};みたいなの欲しいって言われてたので追加した。

1
2
3
4
5
6
7
8
9
10
use Malts::Web::Router::Simple::Declare;
# いままで
get '/' => 'Root#index';
get '' => {controller => 'Root', action => 'index'};

# 新しく追加
get '/' => sub {
    my ($c) = @_;
    $c->res_200();
};

もちろん、get, post, put, delの全部で使える。

例を書いてたのだけど、Malts::Liteみたいなの作る必要なさそう。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use strict;
use warnings;
use parent qw(Malts Malts::Web);
use Malts::Web::Router::Simple::Declare qw(!dispatch);

get '/' => sub {
    shift->res_200;
};

get '/foo' => sub {
    shift->res_200;
};

get '/foo/:user_id' => sub {
    my $c = shift;
    $c->res_200($c->args->{user_id});
};

sub res_200 {
    my ($c, $text) = @_;
    $c->create_response(200, [], $text || 'ok');
}

sub dispatch {
    Malts::Web::Router::Simple::Declare->dispatch(@_)
        or $_[0]->create_response(404, [], ['404 Not Found!']);
}

__PACKAGE__->to_app;

実際に利用するかどうかは置いといて、こういう事も出来るようにはなった。
Controllerにルーティング書いてみる。Catalystを分かりやすくした感じ。
さっきのに比べるとごちゃごちゃしてるように見える。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use strict;
use warnings;

package MyApp::Web;
use parent qw(Malts Malts::Web);

sub res_200 {
    my ($c, $text) = @_;
    $c->create_response(200, [], $text || 'ok');
}

sub dispatch {
    MyApp::Web::Dispatcher->dispatch(@_)
        or $_[0]->create_response(404, [], ['404 Not Found!']);
}

package MyApp::Web::Dispatcher;
use Malts::Web::Router::Simple::Declare;
# ファイルを分割した時のため
# use Module::Find qw(useall);
# useall 'MyApp::Web::Controller';

package MyApp::Web::Controller::Root;
use Malts::Web::Router::Simple::Declare;

get '/' => sub {
    shift->res_200;
};

package MyApp::Web::Controller::Foo;
use Malts::Web::Router::Simple::Declare;

get '/foo' => sub {
    shift->res_200;
};

get '/foo/:user_id' => sub {
    my $c = shift;
    $c->res_200($c->args->{user_id});
};

package main;
MyApp::Web->to_app;

Malts::Web::Router::Simple::Declareって書くのだるいし、Malts::Web::Router::Simpleに変更するかも。

2012年1月27日 金曜日 perl Tags:

Leave a Reply