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