Ok, I don't feel so dirty now. Still need to implement method filtering, such that...
[catagits/CatalystX-DynamicComponent.git] / lib / CatalystX / ModelToControllerReflector.pm
1 package CatalystX::ModelToControllerReflector;
2 use Moose::Role;
3 use namespace::autoclean;
4
5 with 'CatalystX::DynamicComponent' => {
6     name => '_setup_dynamic_controller',
7     pre_immutable_hook => '_setup_dynamic_controller_meta',
8 };
9
10 requires 'setup_components';
11
12 after 'setup_components' => sub { shift->_setup_dynamic_controllers(@_); };
13
14 sub _setup_dynamic_controllers {
15     my ($app) = @_;
16     my @model_names = grep { /::Model::/ } keys %{ $app->components };
17     
18     foreach my $model_name (@model_names) {
19         $app->_reflect_model_to_controller( $model_name, $app->components->{$model_name} );
20     }
21 }
22
23 sub _reflect_model_to_controller {
24     my ( $app, $model_name, $model ) = @_;
25
26     my $class = blessed($app) || $app;
27
28     my $controller_name = $model_name;
29     $controller_name =~ s/::Model::/::Controller::/;
30
31     my $suffix = $model_name;
32     $suffix =~ s/^.*::Model:://;
33
34     my %controller_methods;
35     my $model_methods = $model->meta->get_method_map;
36     delete $model_methods->{new}; # FIXME..
37     delete $model_methods->{meta};
38     foreach my $method_name (keys %$model_methods) {
39             # Note need to pass model name, as the method actually comes from
40             # the underlying model class, not the Catalyst shim class we autogenerated.
41             $controller_methods{$method_name} = $app->generate_reflected_controller_action_method($suffix, $model_methods->{$method_name})
42     }
43
44     $app->_setup_dynamic_controller( $controller_name, {}, \%controller_methods );
45 }
46
47 sub _setup_dynamic_controller_meta {
48     my ($app, $meta) = @_;
49     # Wrong namespace, should be config
50     # and we force it to do a role to
51     # add our crap, allowing the user
52     # to overlay functionality..
53     $meta->superclasses($app . '::ControllerBase', $meta->superclasses);
54 }
55
56 sub generate_reflected_controller_action_method {
57     my ( $app, $model, $method ) = @_;
58     my $method_name = $method->name; # Is it worth passing the actual method object here?
59     sub {
60         my ($self, $c, @args) = @_;
61         $c->res->header('X-From-Model', $model);
62         $c->res->header('X-From-Model-Data', $c->model($model)->$method_name(@args));
63         $c->res->body('OK');
64     };
65 }
66
67 1;
68