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