Commit | Line | Data |
a7caa492 |
1 | package Catalyst::ClassData; |
2 | |
3 | use Moose::Role; |
76aab993 |
4 | use Class::MOP; |
67837eb6 |
5 | use Moose::Util (); |
a7caa492 |
6 | |
7 | sub mk_classdata { |
efbfd430 |
8 | my ($class, $attribute) = @_; |
a7caa492 |
9 | confess("mk_classdata() is a class method, not an object method") |
efbfd430 |
10 | if blessed $class; |
11 | |
12 | my $slot = '$'.$attribute; |
13 | my $accessor = sub { |
eece41a2 |
14 | my $pkg = ref $_[0] || $_[0]; |
67837eb6 |
15 | my $meta = Moose::Util::find_meta($pkg) |
16 | || Moose->init_meta( for_class => $pkg ); |
76721d3c |
17 | if (@_ > 1) { |
ce50990e |
18 | $meta->namespace->{$attribute} = \$_[1]; |
efbfd430 |
19 | return $_[1]; |
20 | } |
76aab993 |
21 | |
eece41a2 |
22 | # tighter version of |
23 | # if ( $meta->has_package_symbol($slot) ) { |
24 | # return ${ $meta->get_package_symbol($slot) }; |
25 | # } |
26 | no strict 'refs'; |
27 | my $v = *{"${pkg}::${attribute}"}{SCALAR}; |
28 | if (defined ${$v}) { |
29 | return ${$v}; |
46d0346d |
30 | } else { |
31 | foreach my $super ( $meta->linearized_isa ) { |
eece41a2 |
32 | # tighter version of same after |
33 | # my $super_meta = Moose::Meta::Class->initialize($super); |
875d8110 |
34 | my $v = ${"${super}::"}{$attribute} ? *{"${super}::${attribute}"}{SCALAR} : undef; |
eece41a2 |
35 | if (defined ${$v}) { |
36 | return ${$v}; |
46d0346d |
37 | } |
efbfd430 |
38 | } |
39 | } |
40 | return; |
a7caa492 |
41 | }; |
76aab993 |
42 | |
43 | confess("Failed to create accessor: $@ ") |
efbfd430 |
44 | unless ref $accessor eq 'CODE'; |
a7caa492 |
45 | |
74c89dea |
46 | my $meta = $class->Class::MOP::Object::meta(); |
30305469 |
47 | confess "${class}'s metaclass is not a Class::MOP::Class" |
48 | unless $meta->isa('Class::MOP::Class'); |
46435d36 |
49 | |
50 | my $was_immutable = $meta->is_immutable; |
51 | $meta->make_mutable if $was_immutable; |
52 | |
a7caa492 |
53 | my $alias = "_${attribute}_accessor"; |
efbfd430 |
54 | $meta->add_method($alias, $accessor); |
55 | $meta->add_method($attribute, $accessor); |
46435d36 |
56 | |
57 | $meta->make_immutable if $was_immutable; |
58 | |
efbfd430 |
59 | $class->$attribute($_[2]) if(@_ > 2); |
a7caa492 |
60 | return $accessor; |
61 | } |
62 | |
63 | 1; |
64 | |
65 | __END__ |
46d0346d |
66 | |
67 | |
68 | =head1 NAME |
69 | |
10011c19 |
70 | Catalyst::ClassData - Class data accessors |
46d0346d |
71 | |
72 | =head1 METHODS |
73 | |
74 | =head2 mk_classdata $name, $optional_value |
75 | |
76 | A moose-safe clone of L<Class::Data::Inheritable> that borrows some ideas from |
77 | L<Class::Accessor::Grouped>; |
78 | |
79 | =head1 AUTHOR |
80 | |
81 | Guillermo Roditi |
82 | |
83 | =head1 COPYRIGHT |
84 | |
85 | This program is free software, you can redistribute it and/or modify it under |
86 | the same terms as Perl itself. |
87 | |
88 | =cut |