/[A3C]/lib/A3C/Cache.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /lib/A3C/Cache.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 227 - (show annotations)
Fri Jun 27 17:53:30 2008 UTC (11 years, 7 months ago) by dpavlin
File size: 1604 byte(s)
Added dir to specify directory in application's var/
in which cache files will go.
1 package A3C::Cache;
2
3 use strict;
4 use warnings;
5
6 use base qw(Jifty::Object Class::Accessor::Fast);
7 __PACKAGE__->mk_accessors( qw(instance dir) );
8 use File::Slurp;
9 use JSON::XS;
10 use Carp qw/confess/;
11
12 =head1 NAME
13
14 A3C::Cache
15
16 =head1 DESCRIPTION
17
18 Fast JSON on-disk cache for long running operations
19
20 B<Doesn't expire any file by itself!>
21
22 =head1 METHODS
23
24 =head2 new
25
26 my $cache = A3C::Cache->new({ instance => 'foobar', dir => 'strix' });
27
28 =head2 cache_path
29
30 Generate unique name for specified values
31
32 my $path = $strix->cache_path( $var, ... );
33
34 Variables have to be path-safe (e.g. use C<uri_encode> if needed)
35
36 =cut
37
38 sub cache_path {
39 my $self = shift;
40
41 #warn "# cache_path",dump( @_ );
42
43 my $dir = $self->dir || 'strix';
44
45 my $path = Jifty::Util->absolute_path( "var/$dir" );
46
47 if ( ! -e $path ) {
48 mkdir $path || die "can't create $path: $!";
49 }
50
51 #warn "## caller = ",dump( (caller(2))[3] );
52 my $uid = (caller(2))[3];
53 $uid =~ s/^[^:]+:://;
54 $uid .= '-' . join('-', @_) if @_;
55 $uid .= '.js';
56
57 return $path . '/' . $self->instance . '-' . $uid;
58 }
59
60 =head2 write_cache
61
62 write_cache( $data, $key_var, ... );
63
64 =cut
65
66 sub write_cache {
67 my $self = shift;
68 my $data = shift || confess "no data?";
69 my $path = $self->cache_path( @_ );
70 write_file( $path, encode_json( $data )) || die "can't save into $path: $!";
71 }
72
73 =head2 read_cache
74
75 my $data = read_cache( 'format-%d', $var ... );
76
77 =cut
78
79 sub read_cache {
80 my $self = shift;
81 my $path = $self->cache_path( @_ );
82 return unless -e $path;
83 #warn "# read_cache( $path )";
84 return decode_json( read_file( $path ) ) || die "can't read $path: $!";
85 }
86
87 1;

  ViewVC Help
Powered by ViewVC 1.1.26