summaryrefslogtreecommitdiff
path: root/Data-MultiValued/t/json.t
blob: ed3a31a5cb7b7e6149ac3b3b8346029cb79f53aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!perl 
use strict;
use warnings;
package Foo;{ 
use Moose;
use Data::MultiValued::AttributeTrait::Tags;
use Data::MultiValued::AttributeTrait::Ranges;
use Data::MultiValued::AttributeTrait::TagsAndRanges;
use Data::Printer;
 
has tt => (
    is => 'rw',
    isa => 'Int',
    traits => ['MultiValued::Tags'],
    default => 3,
    predicate => 'has_tt',
    clearer => 'clear_tt',
);
 
has rr => (
    is => 'rw',
    isa => 'Str',
    traits => ['MultiValued::Ranges'],
    predicate => 'has_rr',
    clearer => 'clear_rr',
);
 
has ttrr => (
    is => 'rw',
    isa => 'Str',
    default => 'default',
    traits => ['MultiValued::TagsAndRanges'],
    predicate => 'has_ttrr',
    clearer => 'clear_ttrr',
);
 
sub new_in_place {
    my ($class,$hash) = @_;
 
    my $self = bless $hash,$class;
 
    for my $attr ($class->meta->get_all_attributes) {
        if ($attr->does('Data::MultiValued::AttributeTrait')) {
            $attr->_rebless_slot($self);
        }
    }
    return $self;
}
 
sub as_hash {
    my ($self) = @_;
 
    my %ret = %$self;
    for my $attr ($self->meta->get_all_attributes) {
        if ($attr->does('Data::MultiValued::AttributeTrait')) {
            my $st = $attr->_as_hash($self);
            if ($st) {
                $ret{$attr->full_storage_slot} = $st;
            }
            else {
                delete $ret{$attr->full_storage_slot};
            }
        }
    }
    return \%ret;
}
 
}
package main; 
use Test::Most 'die';
use Data::Printer;
use JSON::XS;
 
my $opts={tag=>'something'};
 
my $json = JSON::XS->new->utf8;
my $obj = Foo->new(rr=>'foo');
$obj->tt_multi($opts,1234);
my $hash = $obj->as_hash;
note p $hash;
my $str = $json->encode($hash);
note p $str;
 
note "rebuilding";
my $obj2 = Foo->new_in_place($json->decode($str));
 
note p $obj;
note p $obj2;
 
is($obj2->tt,$obj->tt,'tt');
is($obj2->tt_multi($opts),$obj->tt_multi($opts),'tt tagged');
is($obj2->rr,$obj->rr,'rr');
 
done_testing;