Introspection with Perl’s Moose

Posted: August 11, 2010 in Uncategorized

Here’s how to get a free “to_json” method in every object you write. Just extend from a common introspective base class:

use MooseX::Declare;

class BaseObject {

    use signatures;
    use JSON::XS;
        
    has 'id' => (isa => 'Int', is=>'ro', writer => '_id');  
    # and more ...
    
    sub to_json($self) {
        my $result = {};
        foreach my $attr (__PACKAGE__->meta()->get_all_attributes()) {
            $result->{$attr->name()} = $attr->get_value($self);
        }
        return encode_json($result);
    }   
}

Obviously this code needs to check for any objects that it should nest recursively and those that don’t support JSONification*, but that’s coming.

* = is too a word.

Advertisement
Comments
  1. Chris Prather says:

    Or use MooseX::Storage which will recurse your object graph and handle contained objects.

Leave a Reply

Please log in using one of these methods to post your comment:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s