Skip to content

Instantly share code, notes, and snippets.

@tobyink
Created September 20, 2013 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobyink/6634785 to your computer and use it in GitHub Desktop.
Save tobyink/6634785 to your computer and use it in GitHub Desktop.
use v5.16;
use FindBin;
use lib "$FindBin::Bin/lib";
use mop;
use Scalar::Util qw(blessed);
role Dumpable
{
method dump ()
{
state $json_pp = do {
require JSON::PP;
JSON::PP->new->canonical(1)->pretty(1);
};
my %fields = (
'ref($self)' => ref($self),
'$self->id' => $self->id,
);
my $meta = mop::get_meta($self);
for my $attr ($meta->attributes)
{
next unless $attr->has_data_in_slot_for($self);
my $value = $attr->fetch_data_in_slot_for($self);
$fields{$attr->name} =
blessed($value) && $value->isa('mop::object')
? $json_pp->decode($value->dump)
: ref($value) ? "$value" : $value;
}
$json_pp->encode(\%fields);
}
}
class Person with Dumpable
{
has $!name is rw;
has $!age is rw;
}
my $bob = Person->new(name => 'Robert', age => 33);
print $bob->dump;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment