Fix so that superclasses and roles get applied from config. This is where the method...
[catagits/CatalystX-DynamicComponent.git] / lib / CatalystX / DynamicComponent.pm
1 package CatalystX::DynamicComponent;
2 use MooseX::Role::Parameterized;
3 use MooseX::Types::Moose qw/Str CodeRef ArrayRef/;
4 use namespace::autoclean;
5
6 our $VERSION = 0.000001;
7
8 parameter 'name' => (
9     isa => Str,
10     required => 1,
11 );
12
13 parameter 'pre_immutable_hook' => (
14     isa => Str,
15     predicate => 'has_pre_immutable_hook',
16 );
17
18 parameter 'COMPONENT' => (
19     isa => CodeRef,
20     predicate => 'has_custom_component_method',
21 );
22
23 role {
24     my $p = shift;
25     my $name = $p->name;
26     my $pre_immutable_hook = $p->pre_immutable_hook;
27
28     method $name => sub {
29         my ($app, $name, $config, $methods) = @_;
30
31         my $appclass = blessed($app) || $app;
32         my $type = $name;
33         $type =~ s/^${appclass}:://; # FIXME - I think there is shit in C::Utils to do this.
34         $type =~ s/::.*$//;
35
36         my $meta = Moose->init_meta( for_class => $name );
37
38         my @superclasses = @{ $config->{superclasses} || [] };
39         push(@superclasses, 'Catalyst::' . $type) unless @superclasses;
40         $meta->superclasses(@superclasses);
41
42         if (my @roles = @{ $config->{roles}||[] }) {
43             Moose::Util::apply_all_roles( $name, @roles);
44         }
45
46         if ($p->has_custom_component_method) {
47             $meta->add_method(COMPONENT => $p->COMPONENT);
48         }
49
50         $app->$pre_immutable_hook($meta) if $p->has_pre_immutable_hook;
51
52         $methods ||= {};
53         foreach my $name (keys %$methods) {
54             $meta->add_method($name => $methods->{$name});
55         }
56         $meta->make_immutable;
57
58         my $instance = $app->setup_component($name);
59         $app->components->{ $name } = $instance;
60     };
61 };
62
63 1;
64