5 use Method::Generate::Accessor;
7 my $gen = Method::Generate::Accessor->new;
16 use overload '&{}' => sub { sub { 5 } };
20 $gen->generate_method('Foo' => 'one' => { is => 'ro' });
22 $gen->generate_method('Foo' => 'two' => { is => 'rw' });
25 exception { $gen->generate_method('Foo' => 'three' => {}) },
26 qr/Must have an is/, 'No is rejected'
30 exception { $gen->generate_method('Foo' => 'three' => { is => 'purple' }) },
31 qr/Unknown is purple/, 'is purple rejected'
34 for my $setting (qw( default coerce )) {
36 exception { $gen->generate_method('Foo' => 'four' => { is => 'ro', $setting => 5 }) },
37 qr/Invalid $setting/, "$setting - scalar rejected"
41 exception { $gen->generate_method('Foo' => 'five' => { is => 'ro', $setting => [] }) },
42 qr/Invalid $setting/, "$setting - arrayref rejected"
46 exception { $gen->generate_method('Foo' => 'five' => { is => 'ro', $setting => Foo->new }) },
47 qr/Invalid $setting/, "$setting - non-code-convertible object rejected"
51 exception { $gen->generate_method('Foo' => 'six' => { is => 'ro', $setting => sub { 5 } }) },
52 undef, "$setting - coderef accepted"
56 exception { $gen->generate_method('Foo' => 'seven' => { is => 'ro', $setting => bless sub { 5 } => 'Blah' }) },
57 undef, "$setting - blessed sub accepted"
61 exception { $gen->generate_method('Foo' => 'eight' => { is => 'ro', $setting => WithOverload->new }) },
62 undef, "$setting - object with overloaded ->() accepted"
66 exception { $gen->generate_method('Foo' => 'nine' => { is => 'ro', $setting => bless {} => 'Blah' }) },
67 qr/Invalid $setting/, "$setting - object rejected"
71 my $foo = Foo->new(one => 1);
73 is($foo->one, 1, 'ro reads');
74 ok(exception { $foo->one(-3) }, 'ro dies on write attempt');
75 is($foo->one, 1, 'ro does not write');
77 is($foo->two, undef, 'rw reads');
79 is($foo->two, -3, 'rw writes');