Created
July 23, 2013 22:30
-
-
Save krrrr38/6066745 to your computer and use it in GitHub Desktop.
Mojolicious::Liteの一例.WebSocket,jsonレンダリング,js.epを利用した例.以下ではtemplates/assets/javascripts/echo.js.epとしてjsを定義.<script src="<%= url_for('echo-js') %>"></script>として呼び出す事が出来る
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use Mojolicious::Lite; | |
use DBI; | |
# Documentation browser under "/perldoc" | |
plugin 'PODRenderer'; | |
get '/assets/javascripts/echo.js' => { template => 'assets/javascripts/echo', format => 'js' } => 'echo-js'; | |
get '/' => sub { | |
my $self = shift; | |
$self->render('index', params => "hoge"); | |
}; | |
get '/hoge' => sub { | |
my $self = shift; | |
my $params = $self->req->json->{"user"}; | |
$self->render('index'); | |
}; | |
get '/problems' => sub { | |
my $self = shift; | |
my $problem_set_id = $self->param('id') // 1; | |
my $problems = &_get_problems($problem_set_id); | |
$self->render(json => $problems); | |
}; | |
websocket '/echo' => sub { | |
my $self = shift; | |
$self->on(json => sub { | |
my ($self, $hash) = @_; | |
$hash->{msg} = "echo: $hash->{msg}"; | |
$self->send({json => $hash}); | |
}); | |
}; | |
sub _get_problems { | |
my $problem_sets_id = shift; | |
my $DB_NAME = "test"; | |
my $DB_HOST = "localhost"; | |
my $user = 'test'; | |
my $pass = 'test'; | |
my $dbh = DBI->connect("dbi:Pg:dbname=$DB_NAME;host=$DB_HOST", $user, $pass); | |
my $sth = $dbh->prepare("select problem_id, problem, answer, created_at, age, type, problem_set_id from problems as p, problem_sets as ps, problem_inc\ | |
ludes as pi where p.id = pi.problem_id and ps.id = pi.problem_set_id and ps.id = ?"); | |
$sth->execute($problem_sets_id); | |
my @ps = (); | |
while(my $ary_ref = $sth->fetchrow_arrayref){ | |
my ($id, $text, $ans, $at, $age, $type, $ps_id) = @$ary_ref; | |
my %problem = ( | |
id => $id, | |
text => $text, | |
ans => $ans, | |
created_at => $at, | |
age => $age, | |
type => $type, | |
problem_set_id => $ps_id | |
); | |
push(@ps, \%problem); | |
} | |
$dbh->disconnect; | |
return \@ps; | |
}; | |
app->start; | |
__DATA__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment