Skip to content

Instantly share code, notes, and snippets.

@tobyink
Last active August 25, 2020 19:29
Show Gist options
  • Select an option

  • Save tobyink/0779d230469d23cf5ce61be580e4eaca to your computer and use it in GitHub Desktop.

Select an option

Save tobyink/0779d230469d23cf5ce61be580e4eaca to your computer and use it in GitHub Desktop.
Example of marshalling with Zydeco where unmarshalling fails
use v5.16;
use strict;
use warnings;
use JSON::MaybeXS;
use Data::Dumper;
package MyApp {
use Zydeco;
use Carp 'confess';
role ToJSON {
method TO_JSON () {
my %hash = %$self;
return \%hash;
}
}
class Farm with ToJSON {
has fields (
type => 'ArrayRef[Field]',
default => sub { [] },
handles_via => 'Array',
handles => {
'add_field' => 'push',
'count_fields' => 'count',
'last_field' => [ 'get', -1 ],
},
);
}
class Field with ToJSON;
}
my $farm = MyApp->new_farm;
$farm->add_field( MyApp->new_field );
$farm->add_field( MyApp->new_field );
my $json = JSON->new->pretty->canonical->convert_blessed;
my $encoded = $json->encode( $farm );
say $encoded;
my $decoded = MyApp->new_farm( $json->decode($encoded) );
__END__
{
"fields" : [
{},
{}
]
}
Reference [{},{}] did not pass type constraint "ArrayRef[Field]" (in $args->{"fields"}) at (eval 294) line 1
Reference [{},{}] did not pass type constraint "ArrayRef[Field]" (in $args->{"fields"})
"ArrayRef[Field]" constrains each value in the array with "Field"
Not a blessed reference
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment