Catalyst-ActionRole-PseudoCache
view release on metacpan or search on metacpan
lib/Catalyst/ActionRole/PseudoCache.pm view on Meta::CPAN
sub _build_path {
my $self = shift;
my $url = $self->url;
return File::Spec->catfile(split qr{/}, $url);
}
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
my ($args) = @_;
if (my $attr = $args->{attributes}) {
my @args;
if ($attr->{PCTrueCache}) {
@args = (
true_cache => 1,
($attr->{PCKey}
? ( key => $attr->{PCKey}->[0] )
: ()
),
%{$args}
);
croak 'you must not set attributes that are not supported (PCUrl or PCPath) in true cache mode!'
if $attr->{PCUrl} || $attr->{PCPath};
} else {
@args = (
($attr->{PCUrl}
? ( url => $attr->{PCUrl}->[0] )
: ()
),
($attr->{PCPath}
? ( path => $attr->{PCPath}->[0] )
: ()
),
%{$args}
);
croak q(if you don't use true cache mode you must set PCUrl!)
unless $attr->{PCUrl};
carp 'you are not using true cache mode, which is pretty sucky, and more importantly, deprecated'
}
return $class->$orig( @args );
} else {
return $class->$orig(@_);
}
};
around execute => sub {
my $orig = shift;
my $self = shift;
my ( $controller, $c ) = @_;
# do nothing if debug
return $self->$orig(@_)
if ($c->debug);
if ($self->true_cache) {
$self->_true_cache($orig,@_);
} else {
# backup method (for back compat)
$self->_pseudo_cache($orig,@_);
}
};
sub _true_cache {
my ($self, $orig, $controller, $c, @rest) = @_;
my $cache = $c->cache;
if (my $body = $cache->get($self->key)){
$c->response->body($body);
} else {
$self->$orig($controller, $c, @rest);
$cache->set($self->key, $c->response->body);
}
}
sub _pseudo_cache {
my ($self, $orig, $controller, $c, @rest) = @_;
if (!$self->is_cached) {
my $filename = File::Spec->catfile($c->path_to('root'), $self->path);
unlink $filename if stat $filename;
open my $js_fh, '>', $filename;
$self->$orig($controller, $c, @rest);
print {$js_fh} $c->response->body;
close $js_fh;
$self->is_cached(1);
} else {
$c->response->redirect($self->url, 300);
}
}
1;
__END__
=pod
=head1 NAME
Catalyst::ActionRole::PseudoCache - Super simple caching for Catalyst actions
=head1 VERSION
version 1.000003
=head1 SYNOPSIS
package MyApp::Controller::Root;
use Moose;
BEGIN { extends 'Catalyst::Controller::ActionRole' };
# used with Catalyst::Plugin::Cache
sub cache_js :Local Does(PseudoCache) PCTrueCache(1) {
( run in 2.524 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )