in reply to Re^5: Why does changing a Moose attributes' properties remove the around modifier
in thread Why does changing a Moose attributes' properties remove the around modifier

If we suppose you have a good reason to store the IP address an object, then I still find your approach very poor. Don't try to change the behaviour of an existing getter; create a getter that has the behaviour your want.

coerce 'NetAddr::IP' => from 'Str' => via { NetAddr::IP->new($_, '255.255.255.255') }; for my $field (qw( server peer monitor netlog )) { my $object = "${field}_object"; has $object => ( init_arg => $field, is => 'ro', isa => 'NetAddr::IP', coerce => 1, required => 1, handles => { $field => sub { $_[0]->$object->addr }, }, ); }

This makes

$o->server
a shortcut for
$o->server_object->addr

The constructor takes

C->new(server => ...)
rather than
C->new(server_object => ...)
thanks to init_arg.

Thanks to coerce => 1 and the coercion rule, both a NetAddr::IP object and a IP address in string form can be used as the value passed to the constructor.

Replies are listed 'Best First'.
Re^7: Why does changing a Moose attributes' properties remove the around modifier
by mcrose (Beadle) on Jul 20, 2011 at 14:18 UTC

    Yeah, that's a much better way of behaving. I'd missed the documentation that mentioned 'init_arg'. I do need to read through the Class::MOP stuff some time to make sure I'm not missing out on things like this. Thanks for the pointer.

      It's possible to do without init_arg (which I didn't know about for the longest time either), but it's less clear.

      for my $field (qw( server peer monitor netlog )) { my $object = "${field}_object"; has $field => ( reader => $object, isa => 'NetAddr::IP', coerce => 1, required => 1, handles => { $field => sub { $_[0]->$object->addr }, }, ); }