use aliased 'App::Commentry::Comment';
use JSON;
+use File::Spec;
+use File::Path;
+use File::Copy;
use Moo;
has base_dir => (is => 'ro', required => 1);
has _json => (is => 'lazy');
-sub _build__json { JSON->new->utf8->pretty }
+sub _build__json { JSON->new->utf8->pretty->convert_blessed }
has _members => (is => 'lazy');
+sub _filename {
+ my ($self) = @_;
+ File::Spec->catfile($self->base_dir, $self->path.'.json');
+}
+
sub _build__members {
my ($self) = @_;
- my $file = join('/', $self->base_dir, $self->path).'.json';
+ my $file = $self->_filename;
return [] unless -e $file;
my $text = do {
open my $in, '<', $file
[ map Comment->new($_), @{$self->_json->decode($text)} ];
}
+sub _write {
+ my ($self) = @_;
+ my $file = $self->_filename;
+ mkpath((File::Spec->splitpath($file))[1]);
+ open my $out, '>', "${file}.new"
+ or die "Couldn't open ${file}.new to write: $!";
+ print $out $self->_json->encode($self->_members);
+ move("${file}.new", $file);
+}
+
sub flatten {
my ($self) = @_;
@{$self->_members};
App::Commentry::MappedSet->new(source => $self, mapping => $mapping);
}
+sub add {
+ my ($self, $params) = @_;
+ push @{$self->_members}, my $new = Comment->new($params);
+ $self->_write;
+ $new;
+}
+
1;
has base_dir => (is => 'ro', required => 1);
-has _cache => (is => 'ro', default => sub { {} });
+has _cache => (
+ is => 'ro', init_arg => undef,
+ lazy => 1, default => sub { {} },
+ clearer => 'clear_cache'
+);
sub get {
my ($self, $proto) = @_;
use strictures 1;
use Test::More;
+use File::Path;
use aliased 'App::Commentry::CommentStore';
use aliased 'App::Commentry::Comment';
'Existing set loads ok'
);
+my $create = { title => 'Created title', body => 'Created body' };
+
+is_deeply(
+ $store->get({ path => 'create/new' })->add($create),
+ my $new = Comment->new($create),
+ 'Create new ok'
+);
+
+$store->clear_cache;
+
+is_deeply(
+ [ $store->get({ path => 'create/new' })->flatten ],
+ [ $new ],
+ 'Reload ok'
+);
+
+rmtree('t/var/exstore/create');
+
done_testing;