[Perl]Mooseで携帯キャリア判定モジュール

Posted on 24th 2月 2009 in Perl, Web, ソフトウェア, プログラム, モバイル

自作の携帯サイト用アクセス解析ソフト「Episode」の携帯キャリア判定モジュールをMooseでリファクタリングしてみた。色々改善の余地があるコードだけどとりあえず動くので良しとする。

HashRef[Str]型のdefaultの指定方法にめっちゃ苦労した。default = {a=>’a'}ってできなくて、無名サブルーチン使わなきゃいけないらしい。

MooseX::AttributeHelpersを組み込めば、この辺が楽になるのかね?

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
package Episode::Request::UserAgent;
use Moose;
use Perl6::Say;
 
has 'useragent' => (
    is  => 'rw',
    isa => 'Str',
    default => '',
    required => 1,
);
 
 
has 'regex' => (
    is  => 'ro',
    isa => 'HashRef[Str]',
    default => sub {
        {
            docomo   => '^DoCoMo',
            au       => '^(?:KDDI|UP\.Browser\/.+?)-(.+?) ',
            softbank => '^(?:SoftBank|Semulator)',
        }
    },
    required => 1,
);
 
 
__PACKAGE__->meta->make_immutable;
no Moose;
 
sub is_mobile {
    my $self = shift;
    $self->useragent =~ $self->regex->{docomo} ||
    $self->useragent =~ $self->regex->{au} ||
    $self->useragent =~ $self->regex->{softbank}
    ? 1 : 0;
}
 
sub AUTOLOAD {
    my $self = shift;
    our $AUTOLOAD;
    my $pkg = __PACKAGE__ . '::is_';
    $AUTOLOAD =~ s/$pkg//;
    my $regex = $self->regex->{$AUTOLOAD};
    $self->useragent =~ m|$regex| ? 1 : 0;
}
1;
 
my $ua = 'KDDI-HI31 UP.Browser/6.2.0.5 (GUI) MMP/2.0';
my $req = new Episode::Request::UserAgent;
$req->useragent($ua);
say 'mobile? : ',   $req->is_mobile;
say 'docomo? : ',   $req->is_docomo;
say 'au? : ',       $req->is_au;
say 'softbank? : ', $req->is_softbank;

結果

mobile? : 1
docomo? : 0
au? : 1
softbank? : 0

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>