Skip to content

Instantly share code, notes, and snippets.

@syachi
Created December 17, 2014 11:03
Show Gist options
  • Save syachi/acecb0260b335a290f32 to your computer and use it in GitHub Desktop.
Save syachi/acecb0260b335a290f32 to your computer and use it in GitHub Desktop.
やや現代風にカウンターを実装してみる Hokkaido.pm Casual#32
#!/usr/bin/env perl
use Mojolicious::Lite;
use Image::Magick;
use Redis;
get '/' => sub {
my $c = shift;
$c->render('index');
};
get '/counter' => sub {
my $c = shift;
# アトミックなカウンターを実装するのは骨が折れるのでredisを使う
my $redis = Redis->new;
my $count = $redis->incr('counter');
# 桁数分の画像ファイル名を配列に貯めこむ
my @files = map {"img/$_.gif"} split //, "$count";
# 桁数分の画像を連結してpngにする
my $img = Image::Magick->new;
$img->Read(@files);
my $mon = $img->Montage(geometry => '+0 +0', tile => scalar @files . 'x1');
my $blob = $mon->ImageToBlob(magick => 'png');
# 画像を出力する
$c->render(data=>$blob, format => 'png');
};
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!
<br>
<img src="counter">
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment