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;
34 # Check for an 'is' to test strip_name_and_args
35 my $word = $ctx->strip_name;
37 if (defined($word) && ($word eq 'is')) {
38 $traits = $ctx->strip_names_and_args;
41 my $inject = make_proto_unwrap($proto);
43 $inject = $ctx->scope_injector_call().$inject;
45 $ctx->inject_if_block($inject);
47 $name = join('::', Devel::Declare::get_curstash_name(), $name)
48 unless ($name =~ /::/);
49 # for trait testing we're just interested in the trait parse result, not
50 # the method body and its injections
51 $ctx->shadow(sub (&) {
58 $ctx->shadow(sub (&) { shift });
64 my ($test_method1, $test_method2, @test_list);
72 Devel::Declare->setup_for(
74 { method => { const => \&MethodHandlers::parser } }
79 my $class = ref $self || $self;
80 return bless({ @_ }, $class);
84 return (ref $self).': Foo: '.$foo;
87 method has_many_traits() is (Trait1, Trait2(foo => 'bar'), Baz(one, two)) {
91 method has_a_trait() is Foo1 {
95 method upgrade(){ # no spaces to make case pathological
96 bless($self, 'DeclareTest2');
99 method DeclareTest2::bar () {
100 return 'DeclareTest2: bar';
103 $test_method1 = method {
104 return join(', ', $self->{attr}, $_[1]);
107 $test_method2 = method ($what) {
108 return join(', ', ref $self, $what);
111 method main () { return "main"; }
113 @test_list = (method { 1 }, sub { 2 }, method () { 3 }, sub { 4 });
124 ) { return "$foo $bar"; }
134 use Test::More 'no_plan';
136 my $o = DeclareTest->new(attr => "value");
138 isa_ok($o, 'DeclareTest');
140 is($o->{attr}, 'value', '@_ args ok');
142 is($o->foo('yay'), 'DeclareTest: Foo: yay', 'method with argument ok');
144 is($o->main, 'main', 'declaration of package named method ok');
146 is($o->multiline1(3), '33', 'multiline1 proto ok');
147 is($o->multiline2(1,2), '1 2', 'multiline2 proto ok');
148 is($o->multiline3(4,5), '5 4', 'multiline3 proto ok');
152 [['Trait1', undef], ['Trait2', q[foo => 'bar']], ['Baz', 'one, two']],
153 'extracting multiple traits',
159 'extract one trait without arguments',
164 isa_ok($o, 'DeclareTest2');
166 is($o->bar, 'DeclareTest2: bar', 'absolute method declaration ok');
168 is($o->$test_method1('no', 'yes'), 'value, yes', 'anon method with @_ ok');
170 is($o->$test_method2('this'), 'DeclareTest2, this', 'anon method with proto ok');
172 is_deeply([ map { $_->() } @test_list ], [ 1, 2, 3, 4], 'binding ok');