Commit | Line | Data |
31a246e4 |
1 | package Tak::Role::ObjectMangling; |
2 | |
3 | use Scalar::Util qw(weaken); |
4 | use JSON::PP qw(encode_json decode_json); |
5 | |
6 | use Moo::Role; |
7 | |
8 | requires 'inflate'; |
9 | requires 'deflate'; |
10 | |
11 | has encoder_json => (is => 'lazy'); |
12 | has decoder_json => (is => 'lazy'); |
13 | |
14 | sub _build_encoder_json { |
15 | JSON::PP->new->allow_nonref(1)->convert_blessed(1); |
16 | } |
17 | |
18 | sub _build_decoder_json { |
19 | my $self = shift; |
20 | weaken($self); |
21 | JSON::PP->new->allow_nonref(1)->filter_json_single_key_object( |
22 | __proxied_object__ => sub { $self->inflate($_[0]) } |
23 | ); |
24 | } |
25 | |
26 | sub encode_objects { |
27 | my ($self, $data) = @_; |
a3f06b8e |
28 | no warnings 'once'; |
31a246e4 |
29 | local *UNIVERSAL::TO_JSON = sub { $self->deflate($_[0]) }; |
30 | decode_json($self->encoder_json->encode($data)); |
31 | } |
32 | |
33 | sub decode_objects { |
34 | my ($self, $data) = @_; |
35 | $self->decoder_json->decode(encode_json($data)); |
36 | } |
37 | |
a3f06b8e |
38 | 1; |