Make superclasses and roles tests pass
[catagits/CatalystX-DynamicComponent.git] / lib / CatalystX / ModelToControllerReflector.pm
CommitLineData
59fc9d16 1package CatalystX::ModelToControllerReflector;
2use Moose::Role;
abcde601 3use Moose::Util qw/does_role/;
046d763d 4use namespace::autoclean;
59fc9d16 5
53a42ae0 6with 'CatalystX::DynamicComponent' => {
7 name => '_setup_dynamic_controller',
2f61148c 8 pre_immutable_hook => '_setup_dynamic_controller_meta',
53a42ae0 9};
59fc9d16 10
cbc455a6 11requires 'setup_components';
59fc9d16 12
cbc455a6 13after 'setup_components' => sub { shift->_setup_dynamic_controllers(@_); };
59fc9d16 14
15sub _setup_dynamic_controllers {
16 my ($app) = @_;
17 my @model_names = grep { /::Model::/ } keys %{ $app->components };
00b934f1 18
59fc9d16 19 foreach my $model_name (@model_names) {
6a2f1e96 20 $app->_reflect_model_to_controller( $model_name, $app->components->{$model_name} );
59fc9d16 21 }
22}
23
6a2f1e96 24sub _reflect_model_to_controller {
25 my ( $app, $model_name, $model ) = @_;
26
77e54b00 27 my $class = blessed($app) || $app;
28
6a2f1e96 29 my $controller_name = $model_name;
30 $controller_name =~ s/::Model::/::Controller::/;
31
77e54b00 32 my $suffix = $model_name;
33 $suffix =~ s/^.*::Model:://;
34
549d6abc 35 my %controller_methods;
36 my $model_methods = $model->meta->get_method_map;
549d6abc 37 foreach my $method_name (keys %$model_methods) {
abcde601 38 next unless does_role($model_methods->{$method_name}, 'CatalystX::ControllerGeneratingModel::DispatchableMethod');
77e54b00 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.
549d6abc 41 $controller_methods{$method_name} = $app->generate_reflected_controller_action_method($suffix, $model_methods->{$method_name})
77e54b00 42 }
549d6abc 43
0b07685c 44 my $config_name = $controller_name;
45 $config_name =~ s/^[^:]+:://;
46 $app->_setup_dynamic_controller( $controller_name, $app->config->{$config_name}, \%controller_methods );
77e54b00 47}
48
2f61148c 49sub _setup_dynamic_controller_meta {
50 my ($app, $meta) = @_;
00b934f1 51
5cc3fa96 52 Moose::Util::apply_all_roles(
53 $meta => 'CatalystX::ModelToControllerReflector::ControllerRole'
54 );
2f61148c 55}
56
77e54b00 57sub generate_reflected_controller_action_method {
58 my ( $app, $model, $method ) = @_;
59 my $method_name = $method->name; # Is it worth passing the actual method object here?
60 sub {
61 my ($self, $c, @args) = @_;
62 $c->res->header('X-From-Model', $model);
63 $c->res->header('X-From-Model-Data', $c->model($model)->$method_name(@args));
64 $c->res->body('OK');
65 };
59fc9d16 66}
67
681;
69