| 1 | package Class::Component::Component::Autocall::InjectMethod; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Carp::Clan qw/Class::Component/; | ||
| 7 | |||
| 8 | sub register_method { | ||
| 9 | my($self, @methods) = @_; | ||
| 10 | my $class = ref($self) || $self; | ||
| 11 | |||
| 12 | $self->NEXT( register_method => @methods ); | ||
| 13 | while (my($method, $plugin) = splice @methods, 0, 2) { | ||
| 14 | next unless $plugin; | ||
| 15 | no strict 'refs'; | ||
| 16 | no warnings 'redefine'; | ||
| 17 | unless (ref $plugin eq 'HASH') { | ||
| 18 | *{"$class\::$method"} = sub { $plugin->$method(shift, @_) }; | ||
| 19 | next; | ||
| 20 | } | ||
| 21 | |||
| 22 | # extend method | ||
| 23 | my $obj = $plugin; | ||
| 24 | $plugin = $obj->{plugin}; | ||
| 25 | my $real_method = $obj->{method}; | ||
| 26 | next unless $plugin && $real_method; | ||
| 27 | if (ref $real_method eq 'CODE') { | ||
| 28 | *{"$class\::$method"} = sub { $real_method->($plugin, shift, @_) }; | ||
| 29 | } elsif (!ref($real_method)) { | ||
| 30 | *{"$class\::$method"} = sub { $plugin->$real_method(shift, @_) }; | ||
| 31 | } | ||
| 32 | } | ||
| 33 | } | ||
| 34 | |||
| 35 | sub remove_method { | ||
| 36 | my($self, @methods) = @_; | ||
| 37 | $self->NEXT( remove_method => @methods ); | ||
| 38 | while (my($method, $plugin) = splice @methods, 0, 2) { | ||
| 39 | no strict 'refs'; | ||
| 40 | delete ${ref($self) . "::"}{$method}; | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | 1; |