6 package MethodHandlers;
10 use Devel::Declare::Context::Simple;
12 # undef -> my ($self) = shift;
13 # '' -> my ($self) = @_;
14 # '$foo' -> my ($self, $foo) = @_;
16 sub make_proto_unwrap {
18 my $inject = 'my ($self';
20 $proto =~ s/[\r\n\s]+/ /g;
21 $inject .= ", $proto" if length($proto);
22 $inject .= ') = @_; ';
24 $inject .= ') = shift;';
30 my $ctx = Devel::Declare::Context::Simple->new->init(@_);
32 $ctx->skip_declarator;
33 my $name = $ctx->strip_name;
34 my $proto = $ctx->strip_proto;
36 # Check for an 'is' to test strip_name_and_args
37 my $word = $ctx->strip_name;
39 if (defined($word) && ($word eq 'is')) {
40 $traits = $ctx->strip_names_and_args;
43 my $inject = make_proto_unwrap($proto);
45 $inject = $ctx->scope_injector_call().$inject;
47 $ctx->inject_if_block($inject);
49 $name = join('::', Devel::Declare::get_curstash_name(), $name)
50 unless ($name =~ /::/);
51 # for trait testing we're just interested in the trait parse result, not
52 # the method body and its injections
53 $ctx->shadow(sub (&) {
60 $ctx->shadow(sub (&) { shift });
66 my ($test_method1, $test_method2, @test_list);
74 Devel::Declare->setup_for(
76 { method => { const => \&MethodHandlers::parser } }
81 my $class = ref $self || $self;
82 return bless({ @_ }, $class);
86 return (ref $self).': Foo: '.$foo;
89 method has_many_traits() is (Trait1, Trait2(foo => 'bar'), Baz(one, two)) {
93 method has_a_trait() is Foo1 {
97 method upgrade(){ # no spaces to make case pathological
98 bless($self, 'DeclareTest2');
101 method DeclareTest2::bar () {
102 return 'DeclareTest2: bar';
105 $test_method1 = method {
106 return join(', ', $self->{attr}, $_[1]);
109 $test_method2 = method ($what) {
110 return join(', ', ref $self, $what);
113 method main () { return "main"; }
115 @test_list = (method { 1 }, sub { 2 }, method () { 3 }, sub { 4 });
126 ) { return "$foo $bar"; }
138 my $o = DeclareTest->new(attr => "value");
140 isa_ok($o, 'DeclareTest');
142 is($o->{attr}, 'value', '@_ args ok');
144 is($o->foo('yay'), 'DeclareTest: Foo: yay', 'method with argument ok');
146 is($o->main, 'main', 'declaration of package named method ok');
148 is($o->multiline1(3), '33', 'multiline1 proto ok');
149 is($o->multiline2(1,2), '1 2', 'multiline2 proto ok');
150 is($o->multiline3(4,5), '5 4', 'multiline3 proto ok');
154 [['Trait1', undef], ['Trait2', q[foo => 'bar']], ['Baz', 'one, two']],
155 'extracting multiple traits',
161 'extract one trait without arguments',
166 isa_ok($o, 'DeclareTest2');
168 is($o->bar, 'DeclareTest2: bar', 'absolute method declaration ok');
170 is($o->$test_method1('no', 'yes'), 'value, yes', 'anon method with @_ ok');
172 is($o->$test_method2('this'), 'DeclareTest2, this', 'anon method with proto ok');
174 is_deeply([ map { $_->() } @test_list ], [ 1, 2, 3, 4], 'binding ok');