Add comment_if_helptext_not_found feature
[catagits/CatalystX-HelpText.git] / lib / CatalystX / HelpText / ViewRole.pm
1 package CatalystX::HelpText::ViewRole;
2 use Moose::Role;
3 use Try::Tiny;
4 use Moose::Autobox;
5 use namespace::autoclean;
6
7 requires 'expose_methods';
8
9 around expose_methods => sub {
10     my ($orig, $self, @args) = @_;
11     my $m = $self->$orig(@args) || [];
12     [ $m->flatten, 'help_text' ];
13 };
14
15 has helptext_model => (
16     is => 'ro',
17     default => 'Help',
18 );
19
20 has comment_if_helptext_not_found => (
21     is => 'ro',
22     default => 1,
23     isa => 'Bool',
24 );
25
26 sub help_text {
27     my ($self, $c, $key) = @_;
28     my $model = try { $c->model($self->helptext_model) };
29     if (!$model) {
30         $c->log->warn(sprintf("Cannot find the '%s' model for %s", $self->helptext_model, ref($self))) if $c->debug;
31         return;
32     }
33     if (!$model->can('get_help_text_for')) {
34         $c->log->warn(sprintf("Your '%s' model used by '%s' does not have a get_help_text_for method", $self->helptext_model, ref($self))) if $c->debug;
35         return;
36     }
37     try {
38         $model->get_help_text_for($key);
39     }
40     catch {
41         $c->log->warn("Error retrieving help_text key '$key' from model: $_")
42             if $c->debug;
43         return '' unless $self->comment_if_helptext_not_found;
44         return '<!-- Unknown help text: ' . $key . ' -->';
45     };
46 }
47
48 1;
49
50 =head1 NAME
51
52 CatalystX::HelpText::ViewRole - Role to be applied to Views
53
54 =head1 SYNOPSIS
55
56   package MyApp::View::HTML;
57   use Moose;
58
59   extends 'Catalyst::View::TT';
60   with 'CatalystX::HelpText::ViewRole';
61
62   ... then, in your template code ...
63
64   [% helptext('SomeHelpTopic') %]
65
66 =head1 NOTES
67
68 Should work with any view which implements the C<expose_methods> functionality in the same manor
69 that L<Catalyst::View::TT> does, however this has only been tried with that view.
70
71 =head1 SEE ALSO
72
73 =over
74
75 =item L<CatalystX::HelpText>
76
77 =item L<Catalyst::View::TT/expose_methods>
78
79 =back
80
81 =head1 AUTHOR
82
83 Toomas Doran, C<< t0m at state51.co.uk >>
84
85 Cinxgler Mariaca Minda, C<< cinxgler at ci-info.com >>
86
87 =head1 COPYRIGHT
88
89 Copyright Oscar Music and Media 2011.
90
91 =head1 LICENSE
92
93 This sofware is free software, and is licensed under the same terms as perl itself.
94
95 =cut
96