Commit | Line | Data |
59fc9d16 |
1 | package CatalystX::ModelToControllerReflector; |
2 | use Moose::Role; |
046d763d |
3 | use namespace::autoclean; |
59fc9d16 |
4 | |
6a2f1e96 |
5 | with 'CatalystX::DynamicComponent' |
6 | => { alias => { _setup_dynamic_component => '_setup_dynamic_controller' } }; |
59fc9d16 |
7 | |
cbc455a6 |
8 | requires 'setup_components'; |
59fc9d16 |
9 | |
cbc455a6 |
10 | after 'setup_components' => sub { shift->_setup_dynamic_controllers(@_); }; |
59fc9d16 |
11 | |
12 | sub _setup_dynamic_controllers { |
13 | my ($app) = @_; |
14 | my @model_names = grep { /::Model::/ } keys %{ $app->components }; |
15 | |
16 | foreach my $model_name (@model_names) { |
6a2f1e96 |
17 | $app->_reflect_model_to_controller( $model_name, $app->components->{$model_name} ); |
59fc9d16 |
18 | } |
19 | } |
20 | |
6a2f1e96 |
21 | sub _reflect_model_to_controller { |
22 | my ( $app, $model_name, $model ) = @_; |
23 | |
77e54b00 |
24 | my $class = blessed($app) || $app; |
25 | |
6a2f1e96 |
26 | my $controller_name = $model_name; |
27 | $controller_name =~ s/::Model::/::Controller::/; |
28 | |
77e54b00 |
29 | my $suffix = $model_name; |
30 | $suffix =~ s/^.*::Model:://; |
31 | |
32 | my $controller = $app->_setup_dynamic_controller( $controller_name, {}, sub { |
33 | shift->next::method(@_); # Just use the default COMPONENT method |
34 | }); |
35 | my $meta = $controller->meta; |
36 | $meta->make_mutable; # Dirty, I should build the class, add the methods, then |
64ca313b |
37 | # last of all make it a component. The only reason it works |
38 | # like this is that I wrote the simple thing for the model |
39 | # code, abstracted _just_ enough to make it fly with this |
40 | # dirty hack, then stopped. EVERY TIME YOU DO THIS KITTENS DIE |
41 | $meta->remove_method('COMPONENT'); # OMFG This is fucking insane. FIXME! |
42 | $meta->superclasses($app . '::ControllerBase'); # Wrong namespace, should be config |
43 | # and we force it to do a role to |
44 | # add our crap, allowing the user |
45 | # to overlay functionality.. |
77e54b00 |
46 | |
47 | my $methods = $model->meta->get_method_map; |
48 | foreach my $method_name (keys %$methods) { |
49 | $controller->meta->add_method( |
50 | # Note need to pass model name, as the method actually comes from |
51 | # the underlying model class, not the Catalyst shim class we autogenerated. |
52 | $method_name => $app->generate_reflected_controller_action_method($suffix, $methods->{$method_name}) |
53 | ); |
54 | } |
55 | $meta->make_immutable; |
56 | } |
57 | |
58 | sub generate_reflected_controller_action_method { |
59 | my ( $app, $model, $method ) = @_; |
60 | my $method_name = $method->name; # Is it worth passing the actual method object here? |
61 | sub { |
62 | my ($self, $c, @args) = @_; |
63 | $c->res->header('X-From-Model', $model); |
64 | $c->res->header('X-From-Model-Data', $c->model($model)->$method_name(@args)); |
65 | $c->res->body('OK'); |
66 | }; |
59fc9d16 |
67 | } |
68 | |
69 | 1; |
70 | |