More CDI related fail
[catagits/Catalyst-Runtime.git] / lib / Catalyst / ClassData.pm
CommitLineData
a7caa492 1package Catalyst::ClassData;
2
3use Moose::Role;
76aab993 4use Class::MOP;
74c89dea 5use Class::MOP::Object;
a7caa492 6use Scalar::Util 'blessed';
7
8sub mk_classdata {
efbfd430 9 my ($class, $attribute) = @_;
a7caa492 10 confess("mk_classdata() is a class method, not an object method")
efbfd430 11 if blessed $class;
12
13 my $slot = '$'.$attribute;
14 my $accessor = sub {
eece41a2 15 my $pkg = ref $_[0] || $_[0];
74c89dea 16 my $meta = $pkg->Class::MOP::Object::meta();
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 ) {
8a440eba 32 # If there is a code symbol for this attr in a parent class,
33 # then copy it into our package. Is this the correct
34 # fix for C::D::I back-compat? (t0m)
35 my $parent_symbol = *{"${super}::${attribute}"}{CODE} ? \&{"${super}::${attribute}"} : undef;
df3ea11b 36 # FIXME - this is over-enthusiastic?
8a440eba 37 if (defined $parent_symbol) {
38 *{"${pkg}::${attribute}"} = $parent_symbol;
39 }
eece41a2 40 # tighter version of same after
41 # my $super_meta = Moose::Meta::Class->initialize($super);
875d8110 42 my $v = ${"${super}::"}{$attribute} ? *{"${super}::${attribute}"}{SCALAR} : undef;
eece41a2 43 if (defined ${$v}) {
44 return ${$v};
46d0346d 45 }
efbfd430 46 }
47 }
48 return;
a7caa492 49 };
76aab993 50
51 confess("Failed to create accessor: $@ ")
efbfd430 52 unless ref $accessor eq 'CODE';
a7caa492 53
74c89dea 54 my $meta = $class->Class::MOP::Object::meta();
843c9233 55 my $immutable_options;
56 if( $meta->is_immutable ){
57 $immutable_options = $meta->get_immutable_options;
58 $meta->make_mutable;
59 }
a7caa492 60 my $alias = "_${attribute}_accessor";
efbfd430 61 $meta->add_method($alias, $accessor);
62 $meta->add_method($attribute, $accessor);
843c9233 63 if(defined $immutable_options){
11ae7378 64 $meta->make_immutable(%{ $immutable_options });
843c9233 65 }
efbfd430 66 $class->$attribute($_[2]) if(@_ > 2);
a7caa492 67 return $accessor;
68}
69
701;
71
72__END__
46d0346d 73
74
75=head1 NAME
76
77Catalyst::ClassData - Class data acessors
78
79=head1 METHODS
80
81=head2 mk_classdata $name, $optional_value
82
83A moose-safe clone of L<Class::Data::Inheritable> that borrows some ideas from
84L<Class::Accessor::Grouped>;
85
86=head1 AUTHOR
87
88Guillermo Roditi
89
90=head1 COPYRIGHT
91
92This program is free software, you can redistribute it and/or modify it under
93the same terms as Perl itself.
94
95=cut