App-Stash
view release on metacpan or search on metacpan
lib/App/Stash.pm view on Meta::CPAN
print $s->dao->test, "\n";
=head1 WARNING
experimental, use on your own risk :-)
=head1 DESCRIPTION
The purpose of the module is to transparently save stash data (structure)
across application (script) execution. The save is done in L</DESTROY>
method. This has certain limitations. Basically make sure you never store
object in the L</data> as this one may get destroyed before L<App::Stash>
object does.
The module+style is inspired by L<App::Cache>. Unlike L<App::Cache> it uses
L<JSON::Util> for storage and not L<Storable>. The stash is saved to
F<$HOME/.app-name/stash.json>. It is in the "pretty" format so it should be
easy to read and edit. I wanted to go with L<Storable> but using it in
DESTROY method causes C<Segmentation fault> on my Perl.
Warn: no file locking in place, use L<Proc::PID::File> or similar to have just one
instance of program running or send a wish list bug report and wait for
implementation of stash file locking. :)
=cut
use warnings;
use strict;
our $VERSION = '0.02';
use File::HomeDir;
use File::Path qw( mkpath );
use Path::Class;
use JSON::Util;
use base qw( Class::Accessor::Chained::Fast );
__PACKAGE__->mk_accessors(qw( application directory stash_filename ));
=head1 PROPERTIES
application
directory
stash_filename
See L<App::Cache/new> for a description of C<application> and C<directory>.
C<stash_filename> is the full path to the file where stash data will be
stored. All three are optional.
=head1 METHODS
=head2 new()
Object constructor.
=cut
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
unless ( $self->application ) {
my $caller = (caller)[0];
$self->application($caller);
}
unless ( $self->directory ) {
my $dir = dir( home(), "." . $self->_clean( $self->application ));
$self->directory($dir);
}
my $dir = $self->directory;
unless ( -d "$dir" ) {
mkpath("$dir")
|| die "Error mkdiring " . $self->directory . ": $!";
}
unless ( $self->stash_filename ) {
my $stash_filename = file($self->directory , "stash.json" )->stringify;
$self->stash_filename($stash_filename);
}
return $self;
}
=head2 d
Shortcut for L</data>.
=head2 data
Returns reference to the stash data.
=cut
*d = *data;
sub data {
my $self = shift;
$self->load
if (not $self->{'data'});
return $self->{'data'};
}
=head2 dao()
Returns L</data> passed to L<Data::AsObject/dao>. So basically the
data structure becomes an object. See L<Data::AsObject> for details.
Note: L<Data::AsObject> is not compile time dependency. It will be used
if installed. If not the exception will be thrown only when calling L</dao>.
So if you plan to use it, make it a dependency of your module/program.
=cut
sub dao {
my $self = shift;
if (not $INC{'Data/AsObject.pm'}) {
eval 'use Data::AsObject;';
die $@ if $@;
( run in 0.545 second using v1.01-cache-2.11-cpan-98e64b0badf )