Re: Adding traits at runtime

[email protected] ("Dan Harbin")
Newsgroups perl.moose
Message-ID <[email protected]>
Yes, that works.  I guess if $params already contains some traits, I will
have to add 'My::Trait' to the list.  It's a few more lines of code, but
that's no big deal.

Thanks again,
Dan

On Mon, Jun 9, 2008 at 4:13 PM, Stevan Little <
[email protected]> wrote:

>
> On Jun 9, 2008, at 4:40 PM, Dan Harbin wrote:
>
>  Stevan,
>>
>> Thanks for the help.  I am getting the following exception:
>>
>> Can't locate object method "excludes_role" via package "Class::MOP::Class"
>> at lib/Moose/Meta/Role/Application/ToClass.pm line 25.
>>
>> I'm building a class from a YAML spec, and I want to add a trait to every
>> attribute I pull from the YAML file:
>>
>> use YAML;
>> use Moose;
>> use My::Super;
>> use My::Trait;
>>
>> my $file = shift @ARGV;
>> my $yaml = YAML::LoadFile($file);
>>
>> my $rowclass = Moose::Meta::Class->create(
>>    "My::Class",
>>    superclasses => ['My::Super'],
>> );
>>
>> my %columns = @{ $yaml->{columns} };
>> while (my ($name, $params) = each %columns) {
>>  my $attr = Moose::Meta::Attribute->new($name, %$params);
>>  My::Trait->meta->apply($attr);
>>  $rowclass->add_attribute($attr);
>> }
>>
>> Am I doing something wrong?
>>
>
> No, sorry I gave bad advice, the metaclass of the Moose::Meta::Attribute
> instance is a Class::MOP::Class an therefore does not know know about roles.
>
> Why not do:
>
>    $rowclass->add_attribute($name, %$params, traits => [ 'My::Trait' ]);
>
> This should work as expected.
>
> - Stevan
>
>
>
>
>
>
>
>>
>> On Mon, Jun 9, 2008 at 3:24 PM, Stevan Little <
>> [email protected]> wrote:
>> Dan,
>>
>> Something like this maybe?
>>
>> My::Trait->meta->apply(My::Class->meta->get_attribute('foo'));
>>
>> - Stevan
>>
>>
>> On Jun 9, 2008, at 4:21 PM, Dan Harbin wrote:
>>
>> Is there a way to add a trait to an attribute at runtime?  I know it can
>> be
>> done through the "new" method of Moose::Meta::Attribute, but what about
>> adding one after it's been initialized?
>>
>> Thanks,
>> Dan
>>
>>
>>
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.