make this a bit more extensible, for moose's benefit
[gitmo/Class-MOP.git] / lib / metaclass.pm
1
2 package metaclass;
3
4 use strict;
5 use warnings;
6
7 use Carp         'confess';
8 use Scalar::Util 'blessed';
9 use Try::Tiny;
10
11 our $VERSION   = '1.09';
12 $VERSION = eval $VERSION;
13 our $AUTHORITY = 'cpan:STEVAN';
14
15 use Class::MOP;
16
17 sub import {
18     my ( $class, @args ) = @_;
19
20     unshift @args, "metaclass" if @args % 2 == 1;
21     my %options = @args;
22
23     my $should_install_meta = !delete $options{no_meta};
24     my $metaclass = delete $options{metaclass};
25
26     unless ( defined $metaclass ) {
27         $metaclass = "Class::MOP::Class";
28     } else {
29         Class::MOP::load_class($metaclass);
30     }
31
32     ($metaclass->isa('Class::MOP::Class'))
33         || confess "The metaclass ($metaclass) must be derived from Class::MOP::Class";
34
35     # make sure the custom metaclasses get loaded
36     foreach my $key (grep { /_(?:meta)?class$/ } keys %options) {
37         unless ( ref( my $class = $options{$key} ) ) {
38             Class::MOP::load_class($class)
39         }
40     }
41
42     my $package = caller();
43
44     # create a meta object so we can install &meta
45     my $meta = $metaclass->initialize($package => %options);
46     $meta->_add_meta_method if $should_install_meta;
47 }
48
49 1;
50
51 __END__
52
53 =pod
54
55 =head1 NAME
56
57 metaclass - a pragma for installing and using Class::MOP metaclasses
58
59 =head1 SYNOPSIS
60
61   package MyClass;
62
63   # use Class::MOP::Class
64   use metaclass;
65
66   # ... or use a custom metaclass
67   use metaclass 'MyMetaClass';
68
69   # ... or use a custom metaclass
70   # and custom attribute and method
71   # metaclasses
72   use metaclass 'MyMetaClass' => (
73       'attribute_metaclass' => 'MyAttributeMetaClass',
74       'method_metaclass'    => 'MyMethodMetaClass',
75   );
76
77   # ... or just specify custom attribute
78   # and method classes, and Class::MOP::Class
79   # is the assumed metaclass
80   use metaclass (
81       'attribute_metaclass' => 'MyAttributeMetaClass',
82       'method_metaclass'    => 'MyMethodMetaClass',
83   );
84
85   # if we'd rather not install a 'meta' method, we can do this
86   use metaclass no_meta => 1;
87
88 =head1 DESCRIPTION
89
90 This is a pragma to make it easier to use a specific metaclass
91 and a set of custom attribute and method metaclasses. It also
92 installs a C<meta> method to your class as well, if the
93 C<no_meta> option is not specified.
94
95 =head1 AUTHORS
96
97 Stevan Little E<lt>stevan@iinteractive.comE<gt>
98
99 =head1 COPYRIGHT AND LICENSE
100
101 Copyright 2006-2010 by Infinity Interactive, Inc.
102
103 L<http://www.iinteractive.com>
104
105 This library is free software; you can redistribute it and/or modify
106 it under the same terms as Perl itself.
107
108 =cut