CatalystX-CRUD
view release on metacpan or search on metacpan
lib/CatalystX/CRUD/Object/File.pm view on Meta::CPAN
my $class = shift;
my $self = $class->next::method(@_);
my $file = $self->{file} or $self->throw_error("file param required");
$self->{delegate} ||= $self->delegate_class->new(
ref $file eq 'ARRAY' ? @$file : $file );
return $self;
}
=head2 content
The contents of the delegate() file object. Set when you call read().
Set it yourself and call create() or update() as appropriate to write to the file.
=cut
=head2 create
Writes content() to a file. If the file already exists, will throw_error(), so
call it like:
-s $file ? $file->update : $file->create;
Returns the number of bytes written.
=cut
sub create {
my $self = shift;
# write only if file does not yet exist
if ( -s $self->delegate ) {
return $self->throw_error(
$self->delegate . " already exists. cannot create()" );
}
return $self->_write;
}
=head2 read
Slurp contents of file into content(). No check is performed as to whether
the file exists, so call like:
$file->read if -s $file;
=cut
sub read {
my $self = shift;
$self->{content} = $self->delegate->slurp;
return $self;
}
=head2 update
Just like create() only no check is made if the file exists prior to writing
to it. Returns the number of bytes written.
=cut
sub update {
my $self = shift;
return $self->_write;
}
=head2 delete
Remove the file from the filesystem.
=cut
sub delete {
my $self = shift;
return $self->delegate->remove;
}
=head2 is_new
Returns true if the file does not yet exist.
=cut
sub is_new {
my $self = shift;
return defined -s $self->delegate ? 0 : 1;
}
sub _write {
my $self = shift;
my $dir = $self->delegate->dir;
$dir->mkpath;
my $fh = $self->delegate->openw();
print {$fh} $self->content;
$fh->close;
#warn length($self->content) . " bytes written to $self";
return -s $self->delegate;
}
=head2 serialize
Returns the File object as a hashref with 2 keys: file and content.
=cut
sub serialize {
my $self = shift;
return { file => $self->file, content => $self->content };
}
1;
__END__
=head1 AUTHOR
Peter Karman, C<< <perl at peknet.com> >>
=head1 BUGS
( run in 0.975 second using v1.01-cache-2.11-cpan-39bf76dae61 )