Get rid of the insanity of passing the compoenent method as a subref - instead it...
[catagits/CatalystX-DynamicComponent.git] / lib / CatalystX / ModelToControllerReflector.pm
CommitLineData
59fc9d16 1package CatalystX::ModelToControllerReflector;
2use Moose::Role;
046d763d 3use namespace::autoclean;
59fc9d16 4
53a42ae0 5with 'CatalystX::DynamicComponent' => {
6 name => '_setup_dynamic_controller',
7};
59fc9d16 8
cbc455a6 9requires 'setup_components';
59fc9d16 10
cbc455a6 11after 'setup_components' => sub { shift->_setup_dynamic_controllers(@_); };
59fc9d16 12
13sub _setup_dynamic_controllers {
14 my ($app) = @_;
15 my @model_names = grep { /::Model::/ } keys %{ $app->components };
16
17 foreach my $model_name (@model_names) {
6a2f1e96 18 $app->_reflect_model_to_controller( $model_name, $app->components->{$model_name} );
59fc9d16 19 }
20}
21
6a2f1e96 22sub _reflect_model_to_controller {
23 my ( $app, $model_name, $model ) = @_;
24
77e54b00 25 my $class = blessed($app) || $app;
26
6a2f1e96 27 my $controller_name = $model_name;
28 $controller_name =~ s/::Model::/::Controller::/;
29
77e54b00 30 my $suffix = $model_name;
31 $suffix =~ s/^.*::Model:://;
32
cd6bd40d 33 my $controller = $app->_setup_dynamic_controller( $controller_name, {} );
77e54b00 34 my $meta = $controller->meta;
35 $meta->make_mutable; # Dirty, I should build the class, add the methods, then
64ca313b 36 # last of all make it a component. The only reason it works
37 # like this is that I wrote the simple thing for the model
38 # code, abstracted _just_ enough to make it fly with this
39 # dirty hack, then stopped. EVERY TIME YOU DO THIS KITTENS DIE
64ca313b 40 $meta->superclasses($app . '::ControllerBase'); # Wrong namespace, should be config
41 # and we force it to do a role to
42 # add our crap, allowing the user
43 # to overlay functionality..
77e54b00 44
45 my $methods = $model->meta->get_method_map;
46 foreach my $method_name (keys %$methods) {
47 $controller->meta->add_method(
48 # Note need to pass model name, as the method actually comes from
49 # the underlying model class, not the Catalyst shim class we autogenerated.
50 $method_name => $app->generate_reflected_controller_action_method($suffix, $methods->{$method_name})
51 );
52 }
53 $meta->make_immutable;
54}
55
56sub 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 };
59fc9d16 65}
66
671;
68