around, BUILD, MooseX::Object::Pluggable ã®ã¡ã¢
ç§çãªã¡ã¢ã§ãã
around
before, after, augment ã®æ±ç¨çãã¤ãå¼æ°ãæ»ãå¤ãå¤æ´åºæ¥ãã®ãaround
before ã£ã½ã使ãå ´åã¯ã
around 'run' => sub { my $orig = shift; my ($self, @args) = @_; ### process before run ### ããã«ãªããæ¸ã $orig->($self, @args); };
ã¿ããã«æ¸ããç¹å¾´çãªã®ã¯ç¬¬ä¸å¼æ°ã«å
ã®CodeRefãå
¥ã£ã¦ãæããªãã§ãªãªã¸ãã«ãå¼ã³åºãéã«ã$orig->($self, @args) ã®ããã«æ¸ãã
ã¾ã$origã®å¼ã³åºããæ示çã«æ¸ããã®ã§ãå½ç¶æ¸¡ãã¦ãå¼æ°ãæä½ããã°å
ã®ã¡ã½ããå¼ã³åºãã«åæ ãããããæ»ãå¤ã«é¢ãã¦ãåãããã«æä½åºæ¥ããã¤ã¾ãã
around 'calc' => sub { my $orig = shift; my ($self, @args) = @_; my $result = $orig->($self, @args); return $result * 1.05; };
ã¨è¨ã Role ãä½ã£ã¦ with ããã¨ãcalcã®è¨ç®çµæã¯æ¬æ¥ã®è¨ç®çµæã«1.05åããç©ãåããã
BUILD
ã»ã¼ã³ã³ã¹ãã©ã¯ã¿ã¨ãã¦èãã¦è¯ããä½ãåãªãããããã£ã®åæåãªã default ãªãã㯠builder ã使ãã
package BuildSample; use Moose; use Perl6::Say; use Data::Dump qw(dump); has 'foo' => ( is => 'rw', isa => 'Int', required => 1, builder => 'init_foo' ); has 'bar' => ( is => 'rw', isa => 'Str', default => sub { say("init bar"); return ""; } ); sub init_foo { my $self = shift; say("init foo"); $self->foo(12); } sub BUILD { my ($self, $args) = @_; say "[BUILD args] " . dump $args; } __PACKAGE__->meta->make_immutable; package main; use Perl6::Say; my $sample1 = BuildSample->new( foo => 1, bar => "hoge" ); say("-" x 20); my $sample2 = BuildSample->new();
BUILD ã®ç¬¬äºå¼æ°ã« new ã§æ¸¡ãããã©ã¡ã¼ã¿ãããã·ã¥ãªãã¡ã¬ã³ã¹ã¨ãã¦æ ¼ç´ããã¦ãã¿ããã
MooseX::Object::Pluggable
ãã®ã¢ã¸ã¥ã¼ã«ã®ä½¿ãé㯠g:dann:id:dann ãããå§ãã® Devel::REPL ãè¦ãã®ãæã£åãæ©ãã
ãããã MooseX::Object::Pluggable ã®ãã£ã¦ãäºã£ã¦ã®ã¯ããããªã½ã¼ã¹ã§ããã«åããã¨æãã
#!/usr/bin/perl package Foo; use Moose; use Perl6::Say; with 'MooseX::Object::Pluggable'; sub run { say("run"); } package Foo::Plugin::BeforeAction; use Moose::Role; use Perl6::Say; around 'run' => sub { my $orig = shift; my ($self) = @_; say("BeforeAction"); $orig->($self); }; package main; use Perl6::Say; use Data::Dump qw(dump); my $foo = Foo->new; $foo->load_plugin("+Foo::Plugin::BeforeAction"); $foo->run;
ãã©ã°ã¤ã³ã¯ Role ã¨ãã¦å®ç¾©ãã¦ãããload_plugin ã£ã¦ã®ã¯ãã®ä¾ã§ã¯ãFoo ã« with 'Foo::Plugin::BeforeAction' ããã®ã¨åãäºã$foo->meta->roles ã§ç¢ºèªåºæ¥ãã