whole bunch of stuff
[gitmo/Class-MOP.git] / examples / Perl6Attribute.pod
CommitLineData
e2f8b029 1
9ec169fe 2package # hide the package from PAUSE
3 Perl6Attribute;
e2f8b029 4
5use strict;
6use warnings;
7
8our $VERSION = '0.01';
9
10use base 'Class::MOP::Attribute';
11
12sub 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
281;
29
30__END__
31
32=pod
33
34=head1 NAME
35
9ec169fe 36Perl6Attribute - An example attribute metaclass for Perl 6 style attributes
e2f8b029 37
38=head1 SYNOPSIS
39
40 package Foo;
41
42 use Class::MOP 'meta';
43
44 Foo->meta->add_attribute(Perl6Attribute->new('$.foo'));
45 Foo->meta->add_attribute(Perl6Attribute->new('@.bar'));
46 Foo->meta->add_attribute(Perl6Attribute->new('%.baz'));
47
48 sub new {
49 my $class = shift;
5659d76e 50 $class->meta->new_object(@_);
e2f8b029 51 }
52
53=head1 DESCRIPTION
54
55This is an attribute metaclass which implements Perl 6 style
56attributes, including the auto-generating accessors.
57
58This code is very simple, we only need to subclass
59C<Class::MOP::Attribute> and override C<&new>. Then we just
60pre-process the attribute name, and create the accessor name
61and default value based on it.
62
63More advanced features like the C<handles> trait (see
64L<Perl6::Bible/A12>) can be accomplished as well doing the
65same pre-processing approach. This is left as an exercise to
66the reader though (if you do it, please send me a patch
67though, and will update this).
68
69=head1 AUTHOR
70
71Stevan Little E<lt>stevan@iinteractive.comE<gt>
72
73=head1 COPYRIGHT AND LICENSE
74
75Copyright 2006 by Infinity Interactive, Inc.
76
77L<http://www.iinteractive.com>
78
79This library is free software; you can redistribute it and/or modify
80it under the same terms as Perl itself.
81
82=cut