Do More With Recusion (Yet Another Moose Meta Trick)

So I am happily programming along with my nice shiny new 'Serializer' sub that I have cobbled together over the last few post and it is now looking something like this

sub as_hash {
        use Data::Dumper;
        my $self =  shift;
        my ($serialize_on) = @_;
        my $return_hash;
        my @attributes = $self->meta->get_attribute_list();
        foreach my $attr (@attributes){
                my $field = $self->meta->get_attribute($attr);
                        unless ($field->does("MooseX::MetaDescription::Meta::Trait"));
                        unless ($field->description->{serialize} eq $serialize_on );
                my  $value = $self->$attr();        
                if ($field->type_constraint eq 'Bool'){
                   $value = $value ? JSON::true : JSON::false;

        return $return_hash;

and things are working just fine. That is until in the course of todays programming I decided to expand things a little and have my JSON web service deliver some info on mutil-classed characters as well. So then I ran into a problem because of all my serializer now give me is somthing like this


Well I as a quick and dirty solution I just added in elsif and an else to my initial if statement like this

                elsif (ref($value) eq "RPG::ADD::Class") {
                else {

        return $return_hash;


and presto I turn the sub into a simple recursive function. I do love recursion such lovely word rolls right off the lips and sound really cool when said by pirates. Anyway I now get this


This only works for my embedded class because earlier on today I moved the 'as_hash' sub into a role and applied it to the both the 'RPG::ADD::Character' and 'RPG::ADD::Class' class thinking it would be useful.

This will work fine for the moment but I can see this causing me some grief down the line if I have an embedded object other than a 'RPG::ADD::Class' so I would want something that is a little more generic.

Well we will see what tomorrow holds.


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