Nasrudin has asked for the wisdom of the Perl Monks concerning the following question:
Greetings. Apologies if this has been asked before or is easily found by searching (I've tried, honest).
I'm using Moose and trying to apply a trait to an attribute which automatically adds a method into the containing class. I've done this successfully but I'm thinking there's a better way here, and I'd appreciate any feedback provided.
Thanks in advance.
#!/usr/local/bin/perl use strict; use warnings; package Me::Trait::M; use Moose::Role; has mything => ( isa => 'Maybe[Bool]', is => 'rw', default => 0 ); no Moose::Role; package Moose::Meta::Attribute::Custom::Trait::M; sub register_implementation { 'Me::Trait::M'; } package Me; use Moose; has myattr_yes => ( isa => 'Str', is => 'ro', traits => [qw/M/], default => 'this_is_yes', mything => 1, ); has myattr_no => ( isa => 'Str', is => 'ro', default => 'this_is_no', ); sub BUILD { my $self = shift; my $meta = $self->meta; my @attr = $meta->get_all_attributes(); foreach my $at (@attr) { if ($at->does('Me::Trait::M')) { my $closure = $at->name; my $coderef = sub { my $self = shift; print $self->$closure()."\n"; }; $meta->add_method( 'print_' . $closure => $coderef); } } } no Moose; package main; my $f = Me->new(); $f->print_myattr_yes();
UPDATE: Perusing the way that the deprecated MooseX::AttributeHelpers worked led me to understand Tobyink's comment below. Here is a cleaner solution, involving just the role:
package Me::Trait::M; use Moose::Role; has mything => ( isa => 'Maybe[Bool]', is => 'rw', default => 0 ); after 'install_accessors' => sub { my $self = shift; my $realclass = $self->associated_class(); my $closure = $self->name; my $coderef = sub { my $self = shift; print $self->$closure()."\n"; }; $realclass->add_method( 'print_' . $closure => $coderef ); }; no Moose::Role;
Thanks again for the insight!
UPDATE2: Made the idea a bit clearer, no need to loop the attributes since $self is apparently an attribute class
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Moose: Adding methods to a class via attribute traits
by tobyink (Canon) on Jan 17, 2012 at 14:19 UTC | |
by Nasrudin (Acolyte) on Jan 17, 2012 at 21:25 UTC | |
by Nasrudin (Acolyte) on Jan 17, 2012 at 21:56 UTC |