Require Dist::Zilla 4.200016+
[gitmo/Moose.git] / examples / Perl6Attribute.pod
1
2 package # hide the package from PAUSE
3     Perl6Attribute;
4
5 use strict;
6 use warnings;
7
8 our $VERSION = '0.02';
9
10 use base 'Class::MOP::Attribute';
11
12 Perl6Attribute->meta->add_around_method_modifier('new' => sub {
13         my $cont = shift;
14     my ($class, $attribute_name, %options) = @_;
15     
16     # extract the sigil and accessor name
17     my ($sigil, $accessor_name) = ($attribute_name =~ /^([\$\@\%])\.(.*)$/);
18     
19     # pass the accessor name
20     $options{accessor} = $accessor_name;
21     
22     # create a default value based on the sigil
23     $options{default} = sub { [] } if ($sigil eq '@');
24     $options{default} = sub { {} } if ($sigil eq '%');        
25     
26     $cont->($class, $attribute_name, %options);
27 });
28
29 1;
30
31 __END__
32
33 =pod
34
35 =head1 NAME
36
37 Perl6Attribute - An example attribute metaclass for Perl 6 style attributes
38
39 =head1 SYNOPSIS
40
41   package Foo;
42   
43   Foo->meta->add_attribute(Perl6Attribute->new('$.foo'));
44   Foo->meta->add_attribute(Perl6Attribute->new('@.bar'));    
45   Foo->meta->add_attribute(Perl6Attribute->new('%.baz'));    
46   
47   sub new  {
48       my $class = shift;
49       $class->meta->new_object(@_);
50   }
51
52 =head1 DESCRIPTION
53
54 This is an attribute metaclass which implements Perl 6 style 
55 attributes, including the auto-generating accessors. 
56
57 This code is very simple, we only need to subclass 
58 C<Class::MOP::Attribute> and override C<&new>. Then we just 
59 pre-process the attribute name, and create the accessor name 
60 and default value based on it. 
61
62 More advanced features like the C<handles> trait (see 
63 L<Perl6::Bible/A12>) can be accomplished as well doing the 
64 same pre-processing approach. This is left as an exercise to 
65 the reader though (if you do it, please send me a patch 
66 though, and will update this).
67
68 =head1 AUTHORS
69
70 Stevan Little E<lt>stevan@iinteractive.comE<gt>
71
72 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
73
74 =head1 COPYRIGHT AND LICENSE
75
76 Copyright 2006-2008 by Infinity Interactive, Inc.
77
78 L<http://www.iinteractive.com>
79
80 This library is free software; you can redistribute it and/or modify
81 it under the same terms as Perl itself.
82
83 =cut