Skip to content

Commit

Permalink
Support TO_JSON serializer
Browse files Browse the repository at this point in the history
See #43
  • Loading branch information
perlpunk committed Feb 25, 2024
1 parent 8a2ccd5 commit 5a96e62
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/YAML/PP/Schema/Perl.pm
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@ sub new {
my $dumpcode = $args{dumpcode};
$dumpcode = 1 unless defined $dumpcode;
my $classes = $args{classes};
my $serializer = $args{serializer};

my $self = bless {
tags => $tags,
loadcode => $loadcode,
dumpcode => $dumpcode,
classes => $classes,
serializer => $serializer,
}, $class;
}

Expand All @@ -40,12 +42,14 @@ sub register {
my $loadcode = 0;
my $dumpcode = 1;
my $classes;
my $serializer;
if (blessed($self)) {
$tags = $self->{tags};
@$tags = ('!perl') unless @$tags;
$loadcode = $self->{loadcode};
$dumpcode = $self->{dumpcode};
$classes = $self->{classes};
$serializer = $self->{serializer};
}
else {
my $options = $args{options};
Expand Down Expand Up @@ -383,6 +387,13 @@ sub register {
my ($rep, $node) = @_;
my $blessed = blessed $node->{value};
my $tag_blessed = ":$blessed";
if (defined $serializer and $node->{value}->can($serializer)) {
my $data = $node->{value}->$serializer;
$node->{value} = $data;
my $r = $rep->represent_node($node);
return $r;

}
if ($blessed !~ m/^$class_regex$/) {
$tag_blessed = '';
}
Expand Down
38 changes: 38 additions & 0 deletions t/37.schema-perl.t
Original file line number Diff line number Diff line change
Expand Up @@ -376,4 +376,42 @@ EOM
is $yaml, $exp, "Use -loadcode";
};

subtest serializer => sub {
*Dice::TO_JSON = sub {
my ($self) = @_;
my $str = join 'd', @$self;
return $str;
};
my $perl = YAML::PP::Schema::Perl->new(
serializer => 'TO_JSON',
);
my $yp = YAML::PP::Perl->new(
schema => [qw/ + /, $perl],
);
my $o = bless [3,4], "Dice";
my $data = { dice => $o };
my $yaml = $yp->dump_string($data);
my $exp = <<'EOM';
---
dice: 3d4
EOM
is $yaml, $exp, "TO_JSON returns string";

no warnings 'redefine';
*Dice::TO_JSON = sub {
my ($self) = @_;
my $data = { '__dice__' => [@$self] };
return $data;
};
$yaml = $yp->dump_string($data);
$exp = <<'EOM';
---
dice:
__dice__:
- 3
- 4
EOM
is $yaml, $exp, "TO_JSON returns hash";
};

done_testing;

0 comments on commit 5a96e62

Please sign in to comment.