X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FApp%2FCommentry%2FCommentSet.pm;h=85b0c487f6a20eea49648a33d263c44042cbfee1;hb=24b96449f738eaaae2a6f09849e38cfdbbf84aaf;hp=ba41cfcd6a3428c66d4c7dbf11fcf19771b02706;hpb=7356b17a79fb1ec556094c7ae764d97810961e35;p=scpubgit%2FCommentry.git diff --git a/lib/App/Commentry/CommentSet.pm b/lib/App/Commentry/CommentSet.pm index ba41cfc..85b0c48 100644 --- a/lib/App/Commentry/CommentSet.pm +++ b/lib/App/Commentry/CommentSet.pm @@ -2,6 +2,9 @@ package App::Commentry::CommentSet; 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); @@ -9,13 +12,18 @@ has path => (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 @@ -25,6 +33,16 @@ sub _build__members { [ 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}; @@ -36,4 +54,11 @@ sub map { 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;