View/Text/MicroTemplate/PerRequest.pm

filter: Statementstmt 97.0% 66 / 68 Branchbran 50.0% 3 / 6 Conditioncond 33.3% 1 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 95.2% 20 / 21 Podpod n/a totaltotal 90.0% 90 / 100 CC 5 SCAR 3.0
CC
5
Cov
91%
__ANON__
2.1
_create_has_process_error_param
2.1
__ANON__
2.0
CRAP 1.3
« Model/Text/MicroTemplate/ViewData.pm ↑ Summary
1 package Catalyst::View::Text::MicroTemplate::PerRequest;
2  
3 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use CatalystX::InjectComponent;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Catalyst::View::Text::MicroTemplate::_PerRequest;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 our $VERSION = 0.005;
8 1 our $DEFAULT_MT_CLASS = 'Text::MicroTemplate::Extended';
9 1 our $DEFAULT_VIEW_MODEL = 'Text::MicroTemplate::ViewData';
10  
11 1 extends 'Catalyst::View';
12 1 with 'Catalyst::Component::InstancePerContext';
13  
14 2 ▶has merge_stash => (is=>'ro', required=>1, default=>sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
15  
16 1 has path_base => (
17 is=>'ro',
18 required=>1,
19 lazy=>1,
20 builder=>'_build_path_base');
21
22 1 ▶ sub _build_path_base {
Subroutine _build_path_base: called CC=2 SCAR=7.0
23 1 my $self = shift;
24 1 my $root = $self->app->config->{root};
25 1 ▶ die "No directory '$root'" unless -e $root;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $root 0 1 1
26 1 return $root;
27 }
28  
29 2 ▶has extension => (is=>'ro',default=>sub { '.mt' });
Subroutine __ANON__: called CC=1 SCAR=0.0
30 0 ▶has content_type => (is=>'ro', required=>1, default=>sub { 'text/plain' });
Subroutine __ANON__: not called CC=1 SCAR=1.2
31 2 ▶has template_args => (is => 'ro', required=>1, default=>sub { +{} });
Subroutine __ANON__: called CC=1 SCAR=0.0
32 2 ▶has macros => (is => 'ro', required=>1, default=>sub { +{} });
Subroutine __ANON__: called CC=1 SCAR=0.0
33  
34 has mt => (
35 is=>'ro',
36 required=>1,
37 lazy=>1,
38 1 ▶ default=>sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
39 1 my $self = shift;
40 1 ▶ eval "use ${\$self->mt_class}; 1" ||
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
eval "use ${\$self->mt_class;}; 1" or die "Can't use ${\$self->mt_class;}, $@" 1 0 1
41 0 die "Can't use ${\$self->mt_class}, $@";
42  
43 return $self->mt_class->new(
44 extension => $self->extension,
45 include_path => [$self->path_base],
46 template_args => $self->template_args,
47 macros => $self->macros,
48 1 %{$self->mt_init_args});
49 1 });
50  
51 1 ▶sub HANDLE_PROCESS_ERROR {
Subroutine HANDLE_PROCESS_ERROR: called CC=1 SCAR=0.0
52 1 my ($view, $err) = @_;
53 1 my $template = $view->template;
54 1 $view->template('500');
55 1 $view->detach_internal_server_error({ error => "$err", template => $template});
56 }
57  
58 1 has handle_process_error => (
59 is=>'ro',
60 predicate=>'has_handle_process_error');
61  
62 has default_view_model => (
63 is=>'ro',
64 required=>1,
65 2 ▶ default=>sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
66 2 return $DEFAULT_VIEW_MODEL;
67 1 });
68  
69 has mt_class => (
70 is=>'ro',
71 required=>1,
72 2 ▶ default=>sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
73 2 return $DEFAULT_MT_CLASS;
74 1 });
75  
76 2 ▶has mt_init_args => (is=>'ro', required=>1, default=>sub { +{} });
Subroutine __ANON__: called CC=1 SCAR=0.0
77 1 has app => (is=>'ro');
78  
79 has default_template_factory => (
80 is=>'ro',
81 required=>1,
82 2 ▶ default=>sub {
Subroutine __ANON__: called CC=1 SCAR=0.2
83 6 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
84 6 my ($view, $ctx) = @_;
85 return $ctx->stash->{template}
86 6 ▶ || "${\$ctx->action}";
Condition33%1/3
$ctx->stash->{'template'} || "${\$ctx->action;}"
l!l&&r!l&&!r
060
MC/DC0%0/2
$ctx->stash->{'template'} || "${\$ctx->action;}"
$ctx->stash->{'template'} "${\$ctx->action;}"
Truth table33%1/3
A || B
A= $ctx->stash->{'template'}B= "${\$ctx->action;}"
ABresult
1X1
011
000
87 2 };
88 1 });
89  
90 1 ▶sub COMPONENT {
Subroutine COMPONENT: called CC=1 SCAR=0.0
91 1 my ($class, $app, $args) = @_;
92 1 $args = $class->merge_config_hashes($class->config, $args);
93 1 $args->{app} = $app;
94 1 $class->_inject_default_view_model_into($app);
95 1 return $class->new($app, $args);
96 }
97  
98 1 ▶sub _inject_default_view_model_into {
Subroutine _inject_default_view_model_into: called CC=1 SCAR=0.0
99 1 my ($class, $app) = @_;
100 1 CatalystX::InjectComponent->inject(
101 into => $app,
102 component => 'Catalyst::Model::Text::MicroTemplate::ViewData',
103 as => 'Model::Text::MicroTemplate::ViewData' );
104 }
105  
106 6 ▶sub _create_has_process_error_param {
Subroutine _create_has_process_error_param: called CC=2 SCAR=7.2
107 6 my $self = shift;
108 6 ▶ return $self->has_handle_process_error ?
Branch: 1 branch
BranchTrueFalseTotal
$self->has_handle_process_error ? : 6 0 6
109 (handle_process_error=>$self->handle_process_error) : ();
110 }
111  
112 6 ▶sub build_per_context_instance {
Subroutine build_per_context_instance: called CC=1 SCAR=0.0
113 6 my ($self, $c, @args) = @_;
114 6 return bless +{
115 ctx=>$c,
116 parent=>$self,
117 mt=>$self->mt,
118 ($self->_create_has_process_error_param),
119 }, 'Catalyst::View::Text::MicroTemplate::_PerRequest';
120 }
121  
122 1 1;
123  
124 =head1 NAME
125  
126 Catalyst::View::Text::MicroTemplate::PerRequest - JSON View that owns its data
127  
128 =head1 SYNOPSIS
129  
130 MyApp->inject_components(
131 'View::HTML' => { from_component => 'Catalyst::View::Text::MicroTemplate::PerRequest' }
132 );
133  
134 # In a controller...
135  
136 sub root :Chained(/) CaptureArgs(0) {
137 my ($self, $c) = @_;
138 $c->view('HTML')->data->set(z=>1);
139 }
140  
141 sub midpoint :Chained(root) CaptureArgs(0) {
142 my ($self, $c) = @_;
143 $c->view('HTML')->data->set(y=>1);
144 }
145  
146 sub endpoint :Chained(midpoint) Args(0) {
147 my ($self, $c) = @_;
148 $c->view('JSON')->created({
149 a => 1,
150 b => 2,
151 c => 3,
152 });
153 }
154  
155 # template $HOME/root/endpoint.mt
156
157 This is my template
158 Here's some placeholders
159 a => <?= $a ?>
160 b => <?= $b ?>
161 c => <?= $c ?>
162 y => <?= $y ?>
163 z => <?= $z ?>
164  
165  
166 =head1 DESCRIPTION
167  
168 This is a L<Catalyst::View> that uses L<Text::MicroTemplate::Extended> which
169 is a pure Perl templating engine that uses Perl code instead of a dedicated
170 template domain specific language. You may find this a bad idea for large
171 projects where you have a dedicated front end development team (or just a bad
172 idea in general). However I find for smaller projects where the back end programmer
173 does double duty as a UI developer its useful to avoid having to remember yet
174 another DSL just to do output formating. Its reasonable fast and if you control
175 yourself you won't make too much of a mess. You should review L<Text::MicroTemplate::Extended>
176 and L<Text::MicroTemplate> for more on how the template engine works.
177  
178 It differs from other L<Catalyst> views on CPAN (including L<Catayst::View::Text::MicroTemplate>)
179 In that it is a 'per request view' that lets you define a view owned data model
180 for passing information to the view. You may find this a better solution than
181 using the stash although you may also use the stash if you like (there's a template
182 setting for this.)
183  
184 It also generates some local response helpers. You may or may not find this
185 approach leads to cleaner code. Lastly we allow you to more easily override
186 how we generate a default template name. In general I consider this view to be
187 a somewhat experimental approach to solve some common problems that have really irked
188 me about the commonly used approach to views in L<Catalyst> However I do use this in
189 product so I commit to making this stable and safe (just this is not the official proscribed
190 way so you might find some learning curve).
191  
192 A similar style view that produces JSON is L<Catalyst::View::JSON::PerRequest>.
193 In fact this was written so that I could have a view that did HTML with an identical
194 interface as that JSON view, to make it easier in situations where I want to choose
195 a view based on content negotiation (like when doing an API) but would like to keep
196 the rest of the code the same.
197  
198 I consider this approach to be an interesting experiment in alternative ways to
199 use Catalyst views.
200  
201 =head1 METHODS
202  
203 This view defines the following methods
204  
205 =head2 template
206  
207 Used to override the default template, which is derived from the terminating
208 action. You can set this to a particular template name, or an $action.
209  
210 =head2 data (?$model)
211  
212 Used to set the view data model, and/or to called methods on it (for example
213 to set attributes that will later be used in the response.).
214  
215 The default is an injected model based on L<Catalyst::Model::Text::MicroTemplate::ViewData>
216 which you should review for basic usage. I recommend setting it to a custom
217 model that better encapsulates your view data. You may use any model in your
218 L<Catalyst> application. We recommend the model provide a method 'TO_HASH'
219 to provide a read only view of the data suitable for use in a template, but
220 that is optional.
221  
222 You may only set the view data model once. If you don't set it and just call
223 methods on it, the default view model is automatically used.
224  
225 =head2 extra_template_args
226  
227 This is an optional method you may defined in your view class. This is used to
228 add addtional template arguments at request time. Example:
229  
230 sub extra_template_args {
231 my ($self, $view, $c) = @_;
232 return (
233 user => $c->user,
234 )
235 }
236  
237 =head2 res
238  
239 =head2 response
240  
241 $view->response($status, @headers, \%data||$object);
242 $view->response($status, \%data||$object);
243 $view->response(\%data||$object);
244 $view->response($status);
245 $view->response($status, @headers);
246  
247 Used to setup a response. Calling this method will setup an http status, finalize
248 headers and set a body response.
249  
250 =head2 Method '->response' Helpers
251  
252 We map status codes from L<HTTP::Status> into methods to make sending common
253 request types more simple and more descriptive. The following are the same:
254  
255 $c->view->response(200, @args);
256 $c->view->ok(@args);
257  
258 do { $c->view->response(200, @args); $c->detach };
259 $c->view->detach_ok(@args);
260  
261 See L<HTTP::Status> for a full list of all the status code helpers.
262  
263 =head2 render ($data)
264  
265 Given a Perl data will return a string based on the current template.
266  
267 my $html = $c->view->render(@data);
268  
269 =head2 process
270  
271 used as a target for $c->forward. This is mostly here for compatibility with some
272 existing methodology. For example allows using this view with the Renderview action
273 class (common practice). I'd consider it a depracated approach, personally.
274  
275 =head1 template_factory
276  
277 Inherits a default value from L</default_template_factory>.
278  
279 This is a subroutine reference that is used to generate a template name when you don't
280 set one via the L</template> setter (this is the common case, to let the view make
281 the template choice for you). The common way to do this is to choose a template name
282 base on the terminal action name, for example here is the default setting for this
283 attribute:
284  
285 return sub {
286 my ($view, $ctx) = @_;
287 return $ctx->stash->{template}
288 || "${\$ctx->action}";
289 };
290  
291 The subroutine reference will be called with two arguments, the view instance object
292 and the current context object. This should allow you to experiment with new ideas
293 in choosing a default. For example I often find it valuable to distinguish templates
294 not just based on the action path, but also on the response status. That way I can
295 set a default based on something like:
296  
297 return sub {
298 my ($view, $ctx) = @_;
299 return $ctx->response->status > 299 ?
300 "${\$ctx->action}_${\$ctx->res->status}" :
301 "${\$ctx->action}";
302 };
303  
304 That way if an action returns for various status, you can distinguish between OK and
305 error or exception responses.
306  
307 BTW, this complication points out that it is possible that the idea of allowing a view
308 to set a default template via its internal logic is suspect. The issue here is that
309 if you are seeking to write actions that can be used across different views (like an HTML
310 view that needs a template and a JSON view that doesn't) you really prefer to not have
311 code in your action that dictates a template choice.
312  
313 =head1 ATTRIBUTES
314  
315 This View defines the following attributes that can be set during configuration
316  
317 =head2 merge_stash
318  
319 Boolean, defaults to false. If enabled merges anything in $c->stash to
320 the template arguments. Useful if you love the stash or have a situation
321 where you want to start using this view in an existing application that makes
322 extensive use of stash.
323  
324 =head2 path_base
325  
326 Location of your templates. Defaults to whatever $application->config->{root}
327 is.
328  
329 =head2 extension
330  
331 File extention that your templates use. Defaults to ".mt". Please note the '.'
332 is required.
333  
334 =head2 content_type
335  
336 The default content type of your view. Used when providing a response and the
337 content type is currently undefined. Defaults to 'text/plain'.
338  
339 =head2 template_args
340  
341 An option hashref of arguments that are always provided to your template. See
342 L<https://metacpan.org/pod/Text::MicroTemplate::Extended#template_args1> for more.
343  
344 Your template always gets an arg '$c' which is the current context. You may also
345 provide per context template args by providing a method 'extra_template_args'. The
346 advantage of that approach is that method will get the context and other objects
347 as arguments which makes it easier to provide context sensitive values.
348  
349 =head2 default_template_factory
350  
351 Default value for L</template_factory>. Useful if you want a global override for
352 this.
353  
354 =head2 macros
355  
356 See L<https://metacpan.org/pod/Text::MicroTemplate::Extended#Macro>
357  
358 =head2 mt
359  
360 This is the L<Text::MicroTemplate::Extended> object. You probably want to leave this
361 alone but you can set it as you wish as long as you provide a compatible interface.
362 You may find this useful for things like mocking objects during testing.
363  
364 =head2 default_view_model
365  
366 The L<Catalyst> model that is the default model for holding information to
367 pass to the view. The default is L<Catalyst::Model::Text::MicroTemplate::ViewData>
368 which exposes a stash like interface based on L<Data::Perl::Role::Collection::Hash>
369 which is good as a basic interface but you may prefer to try a define a more
370 strict view model interface.
371  
372 If you create your own view model, it should define a method, 'TO_HASH' to
373 provide a hash suitable to pass as arguments to the template. This allows you
374 to separate the view model from the data passed. If you don't define such a
375 method your view model object will be passed to the template as the first
376 argument in '@_';
377  
378 =head2 mt_class
379  
380 The class used to create the L</mt> object. Defaults to L<Text::MicroTemplate::Extended>
381 You can set this to whatever you wish but it should be a compatible interface.
382  
383 =head2 mt_init_args
384  
385 Arguments used to initialize the L</mt_class> in L</mt>. Should be a hashref.
386 See L<Text::MicroTemplate::Extended> for available options
387  
388 =head2 handle_process_error
389  
390 A reference to a subroutine that is called when there is a failure to render
391 the data given. This can be used globally as an attribute
392 on the defined configuration for the view, and you can set it or overide the
393 global settings on a context basis.
394  
395 Setting this optional attribute will capture and handle error conditions. We
396 will NOT bubble the error up to the global L<Catalyst> error handling (we don't
397 set $c->error for example). If you want that you need to set it yourself in
398 a custom handler, or don't define one.
399  
400 The subroutine receives two arguments: the view object and the exception. You
401 must setup a new, valid response. For example:
402  
403 package MyApp::View::HTML;
404  
405 use Moo;
406 extends 'Catalyst::View::Text::MicroTemplate::PerRequest';
407  
408 package MyApp;
409  
410 use Catalyst;
411  
412 MyApp->config(
413 default_view =>'HTML',
414 'View::HTML' => {
415 handle_process_error => sub {
416 my ($view, $err) = @_;
417 $view->template('500bad_request'); # You need to create this template...
418 $view->detach_bad_request({ err => "$err"});
419 },
420 },
421 );
422  
423 MyApp->setup;
424  
425 Or setup/override per context. Useful when you want to control the error
426 message carefully based on URL.
427  
428 sub error :Local Args(0) {
429 my ($self, $c) = @_;
430  
431 $c->view->handle_process_error(sub {
432 my ($view, $err) = @_;
433 $view->template('500bad_request');
434 $view->detach_bad_request({ err => "$err"});
435 });
436  
437 $c->view->ok( $bad_data );
438 }
439  
440 B<NOTE> If you mess up the return value (you return something that can't be
441 encoded) a second exception will occur which will NOT be handled and will then
442 bubble up to the main application.
443  
444 B<NOTE> The view package contains a global function to a usable default
445 error handler, should you wish to use something consistent and reasonably
446 valid. Example:
447  
448 MyApp->config(
449 default_view =>'HTML',
450 'View::HtML' => {
451 handle_encode_error => \&Catalyst::View::Text::MicroTemplate::HANDLE_PROCESS_ERROR,
452 },
453 );
454  
455 The example handler is defined like this:
456  
457 sub HANDLE_PROCESS_ERROR {
458 my ($view, $err) = @_;
459 $view->template('500'); # you need to create a '500.mt' in your template root directory
460 $view->detach_internal_server_error({ error => "$err"});
461 }
462  
463 =head1 UTF-8 NOTES
464  
465 Generally a view should not do any encoding since the core L<Catalyst>
466 framework handles all this for you. L<Text::MicroTemplate> opens your
467 files with the utf-8 IO layer so you should be able to include wide character
468 literals in your templates and everything should 'just work' with any recent
469 L<Catalyst>. As a result this template offers no method to do character
470 encoding. Please raise an issue in the bug tracker if you have special unmet
471 needs.
472  
473 =head1 SEE ALSO
474  
475 L<Catalyst>, L<Catalyst::View>, L<Catalyst::View::Text::MicroTemplate>,
476 L<CatalystX::InjectComponent>, L<Catalyst::Component::InstancePerContext>,
477 L<Text::MicroTemplate::Extended>
478  
479 =head1 AUTHOR
480
481 John Napiorkowski L<email:jjnapiork@cpan.org>
482
483 =head1 COPYRIGHT & LICENSE
484
485 Copyright 2016, John Napiorkowski L<email:jjnapiork@cpan.org>
486
487 This library is free software; you can redistribute it and/or modify it under
488 the same terms as Perl itself.
489  
490 =cut
« Model/Text/MicroTemplate/ViewData.pm ↑ Summary