Commit | Line | Data |
38bf2a25 |
1 | |
2 | package metaclass; |
3 | |
4 | use strict; |
5 | use warnings; |
6 | |
7 | use Carp 'confess'; |
b5ae7c00 |
8 | use Class::Load 'load_class'; |
38bf2a25 |
9 | use Scalar::Util 'blessed'; |
10 | use Try::Tiny; |
11 | |
38bf2a25 |
12 | use Class::MOP; |
13 | |
14 | sub import { |
15 | my ( $class, @args ) = @_; |
16 | |
17 | unshift @args, "metaclass" if @args % 2 == 1; |
18 | my %options = @args; |
19 | |
20 | my $meta_name = exists $options{meta_name} ? $options{meta_name} : 'meta'; |
21 | my $metaclass = delete $options{metaclass}; |
22 | |
23 | unless ( defined $metaclass ) { |
24 | $metaclass = "Class::MOP::Class"; |
25 | } else { |
b5ae7c00 |
26 | load_class($metaclass); |
38bf2a25 |
27 | } |
28 | |
29 | ($metaclass->isa('Class::MOP::Class')) |
30 | || confess "The metaclass ($metaclass) must be derived from Class::MOP::Class"; |
31 | |
32 | # make sure the custom metaclasses get loaded |
33 | foreach my $key (grep { /_(?:meta)?class$/ } keys %options) { |
34 | unless ( ref( my $class = $options{$key} ) ) { |
b5ae7c00 |
35 | load_class($class) |
38bf2a25 |
36 | } |
37 | } |
38 | |
39 | my $package = caller(); |
40 | |
41 | # create a meta object so we can install &meta |
42 | my $meta = $metaclass->initialize($package => %options); |
43 | $meta->_add_meta_method($meta_name) |
44 | if defined $meta_name; |
45 | } |
46 | |
47 | 1; |
48 | |
49 | # ABSTRACT: a pragma for installing and using Class::MOP metaclasses |
50 | |
51 | __END__ |
52 | |
53 | =pod |
54 | |
55 | =head1 SYNOPSIS |
56 | |
57 | package MyClass; |
58 | |
59 | # use Class::MOP::Class |
60 | use metaclass; |
61 | |
62 | # ... or use a custom metaclass |
63 | use metaclass 'MyMetaClass'; |
64 | |
65 | # ... or use a custom metaclass |
66 | # and custom attribute and method |
67 | # metaclasses |
68 | use metaclass 'MyMetaClass' => ( |
69 | 'attribute_metaclass' => 'MyAttributeMetaClass', |
70 | 'method_metaclass' => 'MyMethodMetaClass', |
71 | ); |
72 | |
73 | # ... or just specify custom attribute |
74 | # and method classes, and Class::MOP::Class |
75 | # is the assumed metaclass |
76 | use metaclass ( |
77 | 'attribute_metaclass' => 'MyAttributeMetaClass', |
78 | 'method_metaclass' => 'MyMethodMetaClass', |
79 | ); |
80 | |
81 | # if we'd rather not install a 'meta' method, we can do this |
82 | use metaclass meta_name => undef; |
83 | # or if we'd like it to have a different name, |
84 | use metaclass meta_name => 'my_meta'; |
85 | |
86 | =head1 DESCRIPTION |
87 | |
88 | This is a pragma to make it easier to use a specific metaclass |
89 | and a set of custom attribute and method metaclasses. It also |
90 | installs a C<meta> method to your class as well, unless C<undef> |
91 | is passed to the C<meta_name> option. |
92 | |
b5d324aa |
93 | Note that if you are using Moose, you most likely do B<not> want |
94 | to be using this - look into L<Moose::Util::MetaRole> instead. |
95 | |
38bf2a25 |
96 | =cut |