Created
September 20, 2013 08:35
-
-
Save tobyink/6634785 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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