When it comes to maintaining state I don't see much difference between runtime trait and statically applied trait. As far as I remember the original paper the traits are stateless by nature. So IMHO what you try to do is breaking the traits :-)
But your need is also very natural. I often use Class::Trait and many of my traits would like to have their state variables (usually class or instance accessors).
I solve their wish by a subroutine in the trait (currently named build_class) which I call immediately after the trait is applied. The build_class then modifies the class according to trait's needs.
Class::Trait->apply( $some_class, $some_trait ); my $build_class_sub = $some_trait->can('build_class'); $build_class_sub->($some_class);
Inside the trait I have, for example:
sub build_class { my ($class) = @_; $class->mk_accessors( qw(smb_hostname) ); $class->mk_accessors( qw(smb_username) ); ... }
I guess that with your inside out approach you would probably need something like:
sub build_class { my ($class) = @_; my $destructor = sub { my ($this) = @_; delete $is_selected{ get_obj_id($this) }; }; $class->register_destructor($destructor); }
I know that this approach is not very traity, but my primary goal is to find a consistent and clear way to build my classes not to use pure traits.
There is also somehow complementary issue I need to solve with traits: fixing the name of applying class in the trait. In other words I need my __PACKAGE__ in the trait.
Imagine few logging functions - perfect task for traits. One of them is the logging path for the module. Implemented in class it would look like:
sub logpath { my ($this) = @_; return File::Spec->rel2abs( join( '-', split /::/, __PACKAGE__ ) . + '.log', $this->log_root ); }
All subclasses log into the same file as the class which defined the method. My Durian::Call::Statement logs into $ROOT/Durian-Call-Statement.log as does its Durian::Call::Statement::Incoming subclass.
But how to accomplish this task with trait? The only way I found is to modify the trait symbol table with respect to the class applying the trait immediately before the application. In other words apply a slightly modified trait to every class.
To call preapply subroutine right before the trait methods are collected.
sub preapply { my ($class) = @_; *logpath = sub { my ($this) = @_; return File::Spec->rel2abs( join( '-', split /::/, $class ) . +'.log', $this->log_root ); }; }
With respect to preapply the better name for build_class would be postapply. It sounds good, doesn't it?
Unless someone explains to me that it is a very bad idea I'll try to make my own preapply/postapply Class::Trait subclass.
In reply to Re: Maintaining State with Runtime Traits
by roman
in thread Maintaining State with Runtime Traits
by Ovid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |