| 1 | package MooseX::DeepAccessors; | ||
| 2 | use Moose; | ||
| 3 | use Scalar::Util qw(blessed); | ||
| 4 | our $VERSION = '0.02'; | ||
| 5 | extends 'Moose::Meta::Attribute'; | ||
| 6 | |||
| 7 | has deep_accessors => ( is => 'ro', isa => 'HashRef', default => sub { {} } ); | ||
| 8 | |||
| 9 | after 'attach_to_class' => sub { | ||
| 10 | my ($attr, $class) = @_; | ||
| 11 | |||
| 12 | foreach my $method_name (keys %{ $attr->deep_accessors }) { | ||
| 13 | $class->add_method($method_name, | ||
| 14 | $attr->generate_deep_accessor($attr->deep_accessors->{$method_name}) | ||
| 15 | ); | ||
| 16 | } | ||
| 17 | }; | ||
| 18 | |||
| 19 | sub generate_deep_accessor { | ||
| 20 | my ($attr, $spec) = @_; | ||
| 21 | my $attrname = $attr->name; | ||
| 22 | my ($delegate_method, $callbacks) = %$spec; | ||
| 23 | |||
| 24 | sub { | ||
| 25 | my $self = shift; | ||
| 26 | my $value = $self->$attrname; | ||
| 27 | my @method_params = map { $self->$_ } @$callbacks; | ||
| 28 | return $value->$delegate_method( @method_params ); | ||
| 29 | }; | ||
| 30 | } | ||
| 31 | |||
| 32 | 1; | ||
| 33 | |||
| 34 | package Moose::Meta::Attribute::Custom::MyDeepAccessors; | ||
| 35 | |||
| 36 | sub register_implementation { | ||
| 37 | 'MooseX::DeepAccessors' | ||
| 38 | } | ||
| 39 | |||
| 40 | 1; | ||
| 41 | |||
| 42 | |||
| 43 | __END__ |