made method { ... }; work
[p5sagit/Devel-Declare.git] / t / sugar.t
1 use Devel::Declare;
2
3 BEGIN {
4
5   Devel::Declare->install_declarator(
6     'DeclareTest', 'method', DECLARE_PACKAGE | DECLARE_PROTO,
7     sub {
8       my ($name, $proto) = @_;
9       return 'my $self = shift;' unless defined $proto && $proto ne '@_';
10       return 'my ($self'.(length $proto ? ", ${proto}" : "").') = @_;';
11     },
12     sub {
13       my ($name, $proto, $sub) = @_;
14       if (defined $name && length $name) {
15         unless ($name =~ /::/) {
16           $name = "DeclareTest::${name}";
17         }
18         no strict 'refs';
19         *{$name} = $sub;
20       }
21       return $sub;
22     }
23   );
24
25 }
26
27 my ($test_method1, $test_method2);
28
29 {
30   package DeclareTest;
31
32   method new {
33     my $class = ref $self || $self;
34     return bless({ @_ }, $class);
35   };
36
37   method foo ($foo) {
38     return (ref $self).': Foo: '.$foo;
39   };
40
41   method upgrade () {
42     bless($self, 'DeclareTest2');
43   };
44
45   method DeclareTest2::bar () {
46     return 'DeclareTest2: bar';
47   };
48
49   $test_method1 = method {
50     return join(', ', $self->{attr}, $_[1]);
51   };
52
53   $test_method2 = method ($what) {
54     return join(', ', ref $self, $what);
55   };
56
57 }
58
59 use Test::More 'no_plan';
60
61 my $o = DeclareTest->new(attr => "value");
62
63 isa_ok($o, 'DeclareTest');
64
65 is($o->{attr}, 'value', '@_ args ok');
66
67 is($o->foo('yay'), 'DeclareTest: Foo: yay', 'method with argument ok');
68
69 $o->upgrade;
70
71 isa_ok($o, 'DeclareTest2');
72
73 is($o->bar, 'DeclareTest2: bar', 'absolute method declaration ok');
74
75 is($o->$test_method1('no', 'yes'), 'value, yes', 'anon method with @_ ok');
76
77 is($o->$test_method2('this'), 'DeclareTest2, this', 'anon method with proto ok');