5 use Method::Generate::Accessor;
7 my $gen = Method::Generate::Accessor->new;
16 use overload '&{}' => sub { sub { 5 } }, fallback => 1;
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"
72 exception { $gen->generate_method('Foo' => 'ten' => { is => 'ro', builder => '_build_ten' }) },
73 undef, 'builder - string accepted',
77 exception { $gen->generate_method('Foo' => 'eleven' => { is => 'ro', builder => sub {} }) },
78 qr/Invalid builder/, 'builder - coderef rejected'
82 exception { $gen->generate_method('Foo' => 'twelve' => { is => 'ro', builder => 'build:twelve' }) },
83 qr/Invalid builder/, 'builder - invalid name rejected',
87 exception { $gen->generate_method('Foo' => 'thirteen' => { is => 'ro', builder => 'build::thirteen' }) },
88 undef, 'builder - fully-qualified name accepted',
91 my $foo = Foo->new(one => 1);
93 is($foo->one, 1, 'ro reads');
94 ok(exception { $foo->one(-3) }, 'ro dies on write attempt');
95 is($foo->one, 1, 'ro does not write');
97 is($foo->two, undef, 'rw reads');
99 is($foo->two, -3, 'rw writes');