1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
# Copyright (C) 2008-2010, Sebastian Riedel.
package Mojo::Asset::Memory;
use strict;
use warnings;
use base 'Mojo::Asset';
use Carp 'croak';
use IO::File;
use constant CHUNK_SIZE => $ENV{MOJO_CHUNK_SIZE} || 8192;
# There's your giraffe, little girl.
# I'm a boy.
# That's the spirit. Never give up.
sub new {
my $self = shift->SUPER::new(@_);
$self->{content} = '';
return $self;
}
sub add_chunk {
my ($self, $chunk) = @_;
utf8::encode $chunk if utf8::is_utf8 $chunk;
$self->{content} .= $chunk;
return $self;
}
sub contains { index shift->{content}, shift }
sub get_chunk { substr shift->{content}, shift, CHUNK_SIZE }
sub move_to {
my ($self, $path) = @_;
# Write
my $file = IO::File->new;
$file->open("> $path") or croak qq/Can't open file "$path": $!/;
$file->syswrite($self->{content});
return $self;
}
sub size { length shift->{content} }
sub slurp { shift->{content} }
1;
__END__
=head1 NAME
Mojo::Asset::Memory - In-Memory Asset
=head1 SYNOPSIS
use Mojo::Asset::Memory;
my $asset = Mojo::Asset::Memory->new;
$asset->add_chunk('foo bar baz');
print $asset->slurp;
=head1 DESCRIPTION
L<Mojo::Asset::Memory> is a container for in-memory assets.
=head1 METHODS
L<Mojo::Asset::Memory> inherits all methods from L<Mojo::Asset> and
implements the following new ones.
=head2 C<new>
my $asset = Mojo::Asset::Memory->new;
Construct a new L<Mojo::Asset::Memory> object.
=head2 C<add_chunk>
$asset = $asset->add_chunk('foo bar baz');
Add chunk of data to asset.
=head2 C<contains>
my $position = $asset->contains('bar');
Check if asset contains a specific string.
=head2 C<get_chunk>
my $chunk = $asset->get_chunk($offset);
Get chunk of data starting from a specific position.
=head2 C<move_to>
$asset = $asset->move_to('/foo/bar/baz.txt');
Move asset data into a specific file.
=head2 C<size>
my $size = $asset->size;
Size of asset data in bytes.
=head2 C<slurp>
my $string = $file->slurp;
Read all asset data at once.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.
=cut
|