Do Even more with Meta (Yet Another Moose Meta Trick IV)

Well in my last post I left of with my serializer working for boolean and json and recursing down into itself to work for objects, well one object anyway, and I left it at that with the gaping hole in my code if I need to look at any deeper objects.

Well I am in luck again as 'MooseX::MetaDescription' not only works for 'Attributes' It can also be applied at the 'Class' level.

It is a little more complected than just adding a 'trait' to an attribute or a class as one has to create a base class first and in my case it was like this


package RPG::ADD::Object;

use metaclass 'MooseX::MetaDescription::Meta::Class' => (
    # add class-level metadata
    description => {
        'as' => 'object',
    }
);
use Moose;
1;

Then in my Character class I do


package RPG::ADD::Character;
use Moose;
extends 'RPG::ADD::Object';
with ('RPG::ADD::Types',"RPG::ADD::Util::Serialize'," );
...


Now this is doing something I have been adverse to doing up until this time and that is 'Extending' my class as we can quickly get into Diamond land but I am comfortable with one level.

Some of the extra sharp readers out there would also of noticed that my 'as_hash' sub will now fail at this point


    next
        unless ($field->does("MooseX::MetaDescription::Meta::Trait"));


when it recurses on an object as it does not do the 'Meta::Trait' role. However both this role and and the 'Meta::Class' have a 'description' sub in meta so I can change that if over to


    next
        unless ($field->can("description"));

and problem solved till the next line


     next
        unless ($field->description->{serialize} eq $serialize_on );

As my class description hash will not have a 'serialize' key in it. I can easily fix that like this.


use Moose;
extends 'RPG::ADD::Object';
with ('RPG::ADD::Types',"RPG::ADD::Util::Serialize'," );
__PACKAGE__->meta->description->{'serialize'} = 'tombstone';


And that will add the correct key value pair in my meta description hash. This is of course perfectly allowable and even desirable as long as one does not re-purpose the key value tag pairs later in the game.

Now of course I have to change my if/else a little but this time it is a little more readable


    my  $value = $self->$attr();        

    $value = $value ? JSON::true : JSON::false
       if ($field->type_constraint eq 'Bool');        
    
    $value = $value->as_hash()
       if ($field->description->{as} eq 'object') ;

     $return_hash->{$attr}=$value;

Which seem to work just fine. Noe it would be nice if I could get that 'extends' out of there somehow??

moose_kiss.jpg

Leave a comment

About byterock

user-pic Long time Perl guy, a few CPAN mods allot of work on DBD::Oracle and a few YAPC presentations