Release commit for 0.006022
[p5sagit/Devel-Declare.git] / t / sugar.t
1 use strict;
2 use warnings;
3 use Devel::Declare;
4
5 BEGIN {
6
7   Devel::Declare->install_declarator(
8     'DeclareTest', 'method', DECLARE_PACKAGE | DECLARE_PROTO,
9     sub {
10       my ($name, $proto) = @_;
11 #no warnings 'uninitialized';
12 #warn "NP: ".join(', ', @_)."\n";
13       return 'my $self = shift;' unless defined $proto && $proto ne '@_';
14       return 'my ($self'.(length $proto ? ", ${proto}" : "").') = @_;';
15     },
16     sub {
17       my ($name, $proto, $sub, @rest) = @_;
18 #no warnings 'uninitialized';
19 #warn "NPS: ".join(', ', @_)."\n";
20       if (defined $name && length $name) {
21         unless ($name =~ /::/) {
22           $name = "DeclareTest::${name}";
23         }
24         no strict 'refs';
25         *{$name} = $sub;
26       }
27       return wantarray ? ($sub, @rest) : $sub;
28     }
29   );
30
31 }
32
33 my ($test_method1, $test_method2, @test_list);
34
35 {
36   package DeclareTest;
37
38   method new {
39     my $class = ref $self || $self;
40     return bless({ @_ }, $class);
41   };
42
43   method foo ($foo) {
44     return (ref $self).': Foo: '.$foo;
45   };
46
47   method upgrade(){ # no spaces to make case pathological
48     bless($self, 'DeclareTest2');
49   };
50
51   method DeclareTest2::bar () {
52     return 'DeclareTest2: bar';
53   };
54
55   $test_method1 = method {
56     return join(', ', $self->{attr}, $_[1]);
57   };
58
59   $test_method2 = method ($what) {
60     return join(', ', ref $self, $what);
61   };
62
63   method main () { return "main"; };
64
65   #@test_list = method { 1 }, sub { 2 }, method () { 3 }, sub { 4 };
66
67 }
68
69 use Test::More 0.88;
70
71 my $o = DeclareTest->new(attr => "value");
72
73 isa_ok($o, 'DeclareTest');
74
75 is($o->{attr}, 'value', '@_ args ok');
76
77 is($o->foo('yay'), 'DeclareTest: Foo: yay', 'method with argument ok');
78
79 is($o->main, 'main', 'declaration of package named method ok');
80
81 $o->upgrade;
82
83 isa_ok($o, 'DeclareTest2');
84
85 is($o->bar, 'DeclareTest2: bar', 'absolute method declaration ok');
86
87 is($o->$test_method1('no', 'yes'), 'value, yes', 'anon method with @_ ok');
88
89 is($o->$test_method2('this'), 'DeclareTest2, this', 'anon method with proto ok');
90
91 #warn map { $_->() } @test_list;
92
93 done_testing;