Skip to content

Commit

Permalink
better helper example to demonstrate the use of state variables
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Dec 11, 2012
1 parent c031d93 commit d25f32d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/Mojolicious.pm
Expand Up @@ -417,13 +417,15 @@ Add a new helper that will be available as a method of the controller object
and the application object, as well as a function in C<ep> templates.
# Helper
$app->helper(add => sub { $_[1] + $_[2] });
$app->helper(cache => sub { state $cache = {} });
# Controller/Application
my $result = $self->add(2, 3);
$self->cache->{foo} = 'bar';
my $result = $self->cache->{foo};
# Template
%= add 2, 3
% cache->{foo} = 'bar';
%= cache->{foo}
=head2 C<hook>
Expand Down
3 changes: 3 additions & 0 deletions t/mojolicious/lite_app.t
Expand Up @@ -27,9 +27,12 @@ app->defaults(default => 23);
# Test helpers
helper test_helper => sub { shift->param(@_) };
helper test_helper2 => sub { shift->app->controller_class };
helper test_helper3 => sub { state $cache = {} };
helper dead => sub { die $_[1] || 'works!' };
is app->test_helper('foo'), undef, 'no value yet';
is app->test_helper2, 'Mojolicious::Controller', 'right value';
app->test_helper3->{foo} = 'bar';
is app->test_helper3->{foo}, 'bar', 'right result';

# Test renderer
app->renderer->add_handler(dead => sub { die 'renderer works!' });
Expand Down

0 comments on commit d25f32d

Please sign in to comment.