YALMT (Yet Another Little Moose Trick)

You might of read my last post where I solved a problems with serializing an object to JSON by using 'MooseX::MetaDescription' well go a little deeper into coding today and then ran into this;

 has 'spell_use' =>(
	is		=>'ro',
	isa		=>'Bool',
        default      =>0,

and then this gets turned into JSON with JSON::to_json I get this;


which is fine but it is not really what I want. As we all know that in the programming world '0' and '1' is not always 'true' or 'false', in some languages -1 and 0 are false and only 1 is true, unlike the perfect world of perl where only 0 and "" or maybe '' or is that undef except in the case of an 'index' where -1 is false anyway anything but the previous is true, but then again I digress a little.

The point being is that web service should not be for the exclusive use of Perl programmers so what I really want is this


but now I am back to 'hand' producing my out output again as I will have to find the ones that are to be boolean.

Well how to fix this so I am not writing more and more code?

Well it turns out it is quite simple all I need to do is a little more 'Meta' majick trick from Moose and all I need is one little 'if' statement like this

    my  $value = $self->$attr();
    if ($field->type_constraint eq 'Bool'){
        $value = $value ? JSON::true : JSON::false;

So what am I doing here? Well I am taking advantage of the fact that I have already typed in

has 'spell_use' =>(
	is		=>'ro',
	isa		=>'Bool',
        default      =>0,

so now I get the 'type_constraint' from the meta class of my '$field' which I got with this call a few lines before with this call.

 my $field = $self->meta->get_attribute($attr);

Great another problem solved with less typing by Moose

No if only a Moose could learn how to solve the problem of a doorknob life would be good!


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