Moose 基本

subtypeによる型のカスタマイズ

 package Obj; 
 use Moose;
 use Moose::Util::TypeConstraints; 
 
 subtype 'Obj::Int'
    => as 'Int'
    => where { $_ >= 10 }
    => message { "$_ is under 10" };
 has n => (
    is  => 'rw',
    isa => 'Obj::Int',
 );
 
 package main; 
 my $o = Obj->new;
 $o->n(9);

  • subtypeを使うとMaybe[]が使えなくなる。

coerceによる型の強制変換

 package Obj;
 use Mouse;
 use Mouse::Util::TypeConstraints;
 coerce 'Int'
    => from 'Str'
    => via { 999 };
 
 has n => (
    is => 'rw',
    isa => 'Int',
    coerce => 1,
 );
 
 package main;
 my $o = Obj->new;
 $o->n('abc');
 print $o->n,"\n";

subypeとcoerceを使ってDateTimeアトリビュートを実装

 package Obj;
 use Mouse;
 use Mouse::Util::TypeConstraints;
 use DateTime::Format::Pg;
  subtype 'Obj::DateTime'
    => as 'DateTime';
  coerce 'Obj::DateTime'
    => from 'Str'
    => via { DateTime::Format::Pg->parse_date($_) };
    => from 'Undef'
    => via { DateTime->now };
  has dt => (
    is => 'rw',
    isa => 'Obj::DateTime',
    coerce => 1,
 );
 
 package main;
 my $o = Obj->new;
 $o->dt('2009-02-03');
 print $o->dt->ymd,"\n";

aroundによるゲッターの拡張

 package Obj;
 use Moose;
 has n => (
    is => 'rw',
    isa => 'Int',
 );
 around 'n' => sub {
    my $next = shift;
    my $self = shift;
    return $self->$next . '!' unless @_;
 
    my $arg = shift;
    return $self->$next($arg);
 };
 
 package main;
 my $o = Obj->new;
 $o->n(10);
 print $o->n, "\n"; # 10!とビックリがつく

http://search.cpan.org/perldoc?Moose::Manual::FAQ#How_can_I_inflate/deflate_values_in_accessors?

アトリビュート一覧を取得する

 package Obj;
 use Moose;
 has n => (
    is => 'rw',
 );
 sub attribute_list {
    my $self = shift;
    return $self->meta->get_attribute_list;
 }
 
 package main;
 use Data::Dumper;
 my $o = Obj->new;
 print Dumper $o->attribute_list;

http://search.cpan.org/perldoc?Mouse::Meta::Class

参考


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS