Last active
August 25, 2020 19:29
-
-
Save tobyink/6284dd65465c6020bf05cbc1706ca440 to your computer and use it in GitHub Desktop.
Example of marshalling with Zydeco using coercion to unmarshall the data
This file contains hidden or 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 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 { | |
| method from_hashref ( HashRef $args ) { | |
| return $class->new( $_ ); | |
| } | |
| coerce from HashRef via from_hashref; | |
| } | |
| } | |
| 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) ); | |
| say Dumper($decoded); | |
| __END__ | |
| { | |
| "fields" : [ | |
| {}, | |
| {} | |
| ] | |
| } | |
| $VAR1 = bless( { | |
| 'fields' => [ | |
| bless( {}, 'MyApp::Field' ), | |
| bless( {}, 'MyApp::Field' ) | |
| ] | |
| }, 'MyApp::Farm' ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment