Skip to content

Commit

Permalink
Tie existing data
Browse files Browse the repository at this point in the history
to support add_mapping_resolver and on_create
  • Loading branch information
perlpunk committed Jun 27, 2022
1 parent 9309e89 commit 34e7e7e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
2 changes: 1 addition & 1 deletion lib/YAML/PP/Constructor.pm
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ sub mapping_start_event {
my $preserve_style = $self->preserve_flow_style;
my $preserve_alias = $self->preserve_alias;
if (($preserve_order or $preserve_style or $preserve_alias) and not tied(%$data)) {
tie %$data, 'YAML::PP::Preserve::Hash';
tie %$data, 'YAML::PP::Preserve::Hash', %$data;
}
if ($preserve_style) {
my $t = tied %$data;
Expand Down
24 changes: 19 additions & 5 deletions t/41.custom.schema.t
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,37 @@ use strict;
use warnings;
use Test::More;
use YAML::PP;
use YAML::PP::Common qw/ :PRESERVE /;

use FindBin '$Bin';
use lib "$Bin/lib";

my $yp = YAML::PP->new(
schema => [qw/ :MySchema /],
preserve => PRESERVE_ORDER,
);

my $data = {
o1 => (bless {}, 'Class1'),
};
my $yaml = <<'EOM';
---
o1: !Class1
z: 1
a: 2
y: 3
b: 4
EOM

my $data = $yp->load_string($yaml);

my $yaml = $yp->dump_string($data);
$yaml = $yp->dump_string($data);

cmp_ok($yaml, 'eq', <<EOY, '$data serializes with the schema in t/lib/MySchema.pm');
---
o1: !Class1 ''
o1: !Class1
id: 23
z: 1
a: 2
y: 3
b: 4
EOY

done_testing;
11 changes: 10 additions & 1 deletion t/lib/MySchema.pm
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,22 @@ package MySchema;
my ($self, %args) = @_;
my $schema = $args{schema};

$schema->add_mapping_resolver(
tag => '!Class1',
on_create => sub { return bless { id => 23 }, 'Class1' },
on_data => sub {
my ($constructor, $data, $list) = @_;
%$$data = (%$$data, @$list);
},
);

$schema->add_representer(
class_equals => 'Class1',
code => sub {
my ($representer, $node) = @_;
# $node->{value} contains the object
$node->{tag} = '!Class1';
$node->{ data } = '';
$node->{data} = $node->{value};
return 1;
},
);
Expand Down

0 comments on commit 34e7e7e

Please sign in to comment.