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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
|
use strict;
use warnings;
use Test::More;
{
package Foo;
use Moose;
use Moose::Util::TypeConstraints;
subtype 'UCHash', as 'HashRef[Str]', where {
!grep {/[a-z]/} values %{$_};
};
coerce 'UCHash', from 'HashRef[Str]', via {
$_ = uc $_ for values %{$_};
$_;
};
has hash => (
traits => ['Hash'],
is => 'rw',
isa => 'UCHash',
coerce => 1,
handles => {
set_key => 'set',
},
);
our @TriggerArgs;
has lazy => (
traits => ['Hash'],
is => 'rw',
isa => 'UCHash',
coerce => 1,
lazy => 1,
default => sub { { x => 'a' } },
handles => {
set_lazy => 'set',
},
trigger => sub { @TriggerArgs = @_ },
clearer => 'clear_lazy',
);
}
my $foo = Foo->new;
{
$foo->hash( { x => 'A', y => 'B' } );
$foo->set_key( z => 'c' );
is_deeply(
$foo->hash, { x => 'A', y => 'B', z => 'C' },
'set coerces the hash'
);
}
{
$foo->set_lazy( y => 'b' );
is_deeply(
$foo->lazy, { x => 'A', y => 'B' },
'set coerces the hash - lazy'
);
is_deeply(
\@Foo::TriggerArgs,
[ $foo, { x => 'A', y => 'B' }, { x => 'A' } ],
'trigger receives expected arguments'
);
}
{
package Thing;
use Moose;
has thing => (
is => 'ro',
isa => 'Str',
);
}
{
package Bar;
use Moose;
use Moose::Util::TypeConstraints;
class_type 'Thing';
coerce 'Thing'
=> from 'Str'
=> via { Thing->new( thing => $_ ) };
subtype 'HashRefOfThings'
=> as 'HashRef[Thing]';
coerce 'HashRefOfThings'
=> from 'HashRef[Str]'
=> via {
my %new;
for my $k ( keys %{$_} ) {
$new{$k} = Thing->new( thing => $_->{$k} );
}
return \%new;
};
coerce 'HashRefOfThings'
=> from 'Str'
=> via { [ Thing->new( thing => $_ ) ] };
has hash => (
traits => ['Hash'],
is => 'rw',
isa => 'HashRefOfThings',
coerce => 1,
handles => {
set_hash => 'set',
get_hash => 'get',
},
);
}
{
my $bar = Bar->new( hash => { foo => 1, bar => 2 } );
is(
$bar->get_hash('foo')->thing, 1,
'constructor coerces hash reference'
);
$bar->set_hash( baz => 3, quux => 4 );
is(
$bar->get_hash('baz')->thing, 3,
'set coerces new hash values'
);
is(
$bar->get_hash('quux')->thing, 4,
'set coerces new hash values'
);
}
done_testing;
|