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