Re: attr initializers (Class::MOP and Moose)
[email protected] (Ricardo SIGNES)
| Newsgroups | perl.moose |
|---|---|
| Message-ID | <[email protected]> |
* Stevan Little <[email protected]> [2008-02-06T15:34:54] > On Feb 6, 2008, at 12:18 PM, Ricardo SIGNES wrote: >> The initializer may be a coderef or a method name (referring to a method >> on the >> instance.) It's called like this: >> >> $instance->$initializer($value, $name, $callback); > > What is $name for again? It's the attribute name. This lets you have one initializer for multiple attributes. If my contrived example in tests wasn't so contrived I'd say you could use it and do this: my %mult_for = (foo => 2, bar => 3); my $multer = sub { $_[3]->($value * $mult_for{$_[2]} }; has foo => (initializer => $multer); has bar => (initializer => $multer); I am not strongly attached to passing that in. > I wonder if callback could be optional? And if it is not called, then it > will just use the return value of the initializer sub? I think that is a bad idea. By providing the callback, we make it very easy to *use* the callback, but the default behavior is to do *nothing* but call the initializer. That means that the initializer can choose to make all the set_slot_value calls (or not) that it wants -- no magic return value is needed, then, to say, "seriously I did everything I need, please do not do anything for me." >> I think, but have not tested, that this will also work: >> >> package Example; >> use Moose; >> >> has foo => ( >> is => 'rw', >> setter => 'set_foo', >> initializer => 'set_foo', >> ); > > What exactly would that be useful for? I am not sure I understand without > seeing an example set_foo. I probably should've said: setter => { set_foo => sub { ... } } ...but that's beside the point. The sub might do something like perform complex validation. Actually, here is a better example: has foo => ( setter => 'set_foo', getter => 'get_foo', trigger => sub { ... }, initializer => 'set_foo', ); Now the initial set of the foo attr is done via the setter, which means that the trigger can fire. -- rjbs
signature.asc
(application/pgp-signature, 194 B)
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) iEYEARECAAYFAkeqH9QACgkQHu6P14fNXHPdPACfUq65CkayhbvUFeEhuGXI0eMo GYUAoIaekrWIE+3Y4XKFk/rRpt6Xiocq =oQcf -----END PGP SIGNATURE-----