Mojolicious::LiteでData::Modelを使ってみた

先日1.0にバージョンアップしたMojolicious(::Lite)を本格的に触ってみようとアレコレやってみた。 MojoliciousのWikiにORLiteを使ったサンプルがあったのですが、残念ながらそのままでは日本語には対応していないので、他のORMを使ってみようという、そんな感じです。

SEE ALSO

ほとんどが元ネタのパクリですが。

 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env perl
#utf8
# use Acme::PerlTidy;
package DataModel;
use utf8;
use base 'Data::Model';
use Data::Model::Schema;
use Data::Model::Driver::DBI;
my $dbfile = qq{$0.db};
my $dsn    = qq{dbi:SQLite:dbname=$dbfile};
my $driver = Data::Model::Driver::DBI->new(
    dsn             => $dsn,
    connect_options => {sqlite_unicode => 1,},
);
base_driver($driver);
install_model motorcycles => schema {
    key 'id';
    column id    => int  => {auto_increment => 1};
    column type  => char => {required       => 1};
    column brand => char => {required       => 1};
    column color => char => {required       => 0};
};
unless (-f $dbfile) {
    my $dbh = DBI->connect($dsn, '', '', {RaiseError => 1, PrintError => 0})
        or DBI->errstr;
    for my $sql (__PACKAGE__->as_sqls) {
        $dbh->do($sql) or die $dbh->errstr;
    }
    $dbh->disconnect;
}

package main;
use utf8;
use Mojolicious::Lite;
use Mojo::Util qw/md5_sum/;
app->log->level('debug')->path(qq{$0.log});
app->secret(md5_sum $0 )->log->debug(app->secret);
app->helper(model => sub { my $dbh = DataModel->new });
get '/' => sub {
    my $self       = shift;
    my $model      = $self->model;
    my $motorbikes = [$model->get('motorcycles' => {order => [{type => 'ASC'}],})];
    $self->stash(
        motorbikes => $motorbikes,
        debug      => $self->dumper([$self, $model]),
    );
}        => 'index';
post '/' => sub {
    my $self  = shift;
    my $model = $self->model;
    $model->set(
        'motorcycles' => {
            type  => $self->param('type'),
            brand => $self->param('brand'),
            color => $self->param('color'),
        }
    );
    $self->redirect_to('/');
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head>
<meta charset="<%= app->renderer->encoding %>">
<title>Motorcycles</title>
</head>
<body>
<table>
% foreach my $cycle (@{$motorbikes} ) {
<tr>
<td><%= $cycle->id %></td>
<td><%= $cycle->type %></td>
<td><%= $cycle->brand %></td>
<td><%= $cycle->color %></td>
</tr>
% }
</table>
<p>バイクを登録してください</p>
<p>
<%= form_for '/' => (method => 'post') => begin %>
% foreach (qw/type brand color/) {
<%= uc($_) %>: <%= input_tag $_, 'type' => 'text' %><br />
% }
<%= submit_button 'Submit motorcycle' %>
<% end %>
</p>
<pre><%= $debug %></pre>
</body>
</html>

Comments

comments powered by Disqus