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