4 package MethodHandlers;
8 use Devel::Declare::Context::Simple;
10 # undef -> my ($self) = shift;
11 # '' -> my ($self) = @_;
12 # '$foo' -> my ($self, $foo) = @_;
14 sub make_proto_unwrap {
16 my $inject = 'my ($self';
18 $proto =~ s/[\r\n\s]+/ /g;
19 $inject .= ", $proto" if length($proto);
20 $inject .= ') = @_; ';
22 $inject .= ') = shift;';
28 my $ctx = Devel::Declare::Context::Simple->new->init(@_);
30 $ctx->skip_declarator;
31 my $name = $ctx->strip_name;
32 my $proto = $ctx->strip_proto;
33 my $inject = make_proto_unwrap($proto);
35 $inject = $ctx->scope_injector_call().$inject;
37 $ctx->inject_if_block($inject);
39 $name = join('::', Devel::Declare::get_curstash_name(), $name)
40 unless ($name =~ /::/);
41 $ctx->shadow(sub (&) { no strict 'refs'; *{$name} = shift; });
43 $ctx->shadow(sub (&) { shift });
49 my ($test_method1, $test_method2, @test_list);
57 Devel::Declare->setup_for(
59 { method => { const => \&MethodHandlers::parser } }
64 my $class = ref $self || $self;
65 return bless({ @_ }, $class);
69 return (ref $self).': Foo: '.$foo;
72 method upgrade(){ # no spaces to make case pathological
73 bless($self, 'DeclareTest2');
76 method DeclareTest2::bar () {
77 return 'DeclareTest2: bar';
80 $test_method1 = method {
81 return join(', ', $self->{attr}, $_[1]);
84 $test_method2 = method ($what) {
85 return join(', ', ref $self, $what);
88 method main () { return "main"; }
90 @test_list = (method { 1 }, sub { 2 }, method () { 3 }, sub { 4 });
101 ) { return "$foo $bar"; }
111 use Test::More 'no_plan';
113 my $o = DeclareTest->new(attr => "value");
115 isa_ok($o, 'DeclareTest');
117 is($o->{attr}, 'value', '@_ args ok');
119 is($o->foo('yay'), 'DeclareTest: Foo: yay', 'method with argument ok');
121 is($o->main, 'main', 'declaration of package named method ok');
123 is($o->multiline1(3), '33', 'multiline1 proto ok');
124 is($o->multiline2(1,2), '1 2', 'multiline2 proto ok');
125 is($o->multiline3(4,5), '5 4', 'multiline3 proto ok');
129 isa_ok($o, 'DeclareTest2');
131 is($o->bar, 'DeclareTest2: bar', 'absolute method declaration ok');
133 is($o->$test_method1('no', 'yes'), 'value, yes', 'anon method with @_ ok');
135 is($o->$test_method2('this'), 'DeclareTest2, this', 'anon method with proto ok');
137 is_deeply([ map { $_->() } @test_list ], [ 1, 2, 3, 4], 'binding ok');