Created
July 12, 2009 02:09
-
-
Save lestrrat/145485 to your computer and use it in GitHub Desktop.
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
# モンキーパッチングは万人におすすめできる手法とは思えないのでやらないほうがいいと思うなぁ - lestrrat | |
# http://d.hatena.ne.jp/bingo_nakanishi_perl/20090711/1247331243 | |
package Bar; | |
use Moose; | |
has name => (is => 'ro'); | |
sub say { | |
my $self = shift; | |
print $self->name, "です\n"; | |
} | |
package main; | |
use strict; | |
my $bar1 = Bar->new(name => "パー"); | |
my $bar2 = Bar->new(name => "アホ"); | |
$bar1->say(); | |
$bar2->say(); | |
# $bar1 のインスタンス「のみ」にsay2をはやす | |
# (Traitsでもできるけど、ここは敢えてMooseコアのみで・・・) | |
$bar1->meta->create_anon_class( | |
superclasses => [ $bar1->meta->name ], | |
methods => { | |
say2 => sub { | |
my $self = shift; | |
print $self->name, "やがな\n"; | |
} | |
} | |
)->rebless_instance($bar1); | |
$bar1->say2(); | |
$bar2->say2(); # これはエラー。$bar1にしかsay2をはやしてない |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment