NAME
Mojo::File::Role::Ingest - Add ingest method to a file.
SYNOPSIS
$file = path('file.txt')->with_roles('+Ingest');
# Mojo::Collection
$lines = $file->ingest('Mojo::File::Role::Lines');
@lines;
$file->ingest('+Lines', {}, sub { push @lines, $_ unless m/^#/ });
$ext_to_role = {csv => '+CSV', txt => '+Lines'};
$file->list->each(sub {
$_->ingest(...)
})
DESCRIPTION
Ingesting the contents of a Mojo::File is a common activity and can be
achieved using "slurp" in Mojo::File to read all the data into memory. Parsing
the data in the file is also a common task and Mojo::File::Role::Ingest provides
a useful syntax to delegate to a role that provides a parse
method and have it appropriately consume the file's contents.
A good model is to either return a Mojo::Collection of records from the file or on a record by record basis call a supplied callback.
METHODS
Mojo::File::Role::Ingest composes the following method. The examples below use the included Mojo::File::Role::Lines.
ingest
# Mojo::Collection of lines
$lines = $file->ingest('+Lines');
# same, but change the end of line ($INPUT_RECORD_SEPARATOR)
$lines = $file->ingest('+Lines', {eol => "//\n"});
# use a callback to collect lines
@lines;
$file->ingest('+Lines', {}, sub { push @lines, $_ unless m/^#/ });
# generally
$file->ingest($role, $options, $cb);
"ingest" delegates to the supplied role's parse
method. The
parse
method will be passed the $options
and $cb
.
The $options
hashref will contain the following keys, as a minimum, when
"parse" is called by "ingest" in Mojo::File::Role::Ingest.
-
encoding
The encoding to "decode" in Mojo::Util with defaulting to
UTF-8
. -
eol
The end of line string defaulting to
$/
-
is_large
A Boolean flag to notify if the file has a byte size larger than
MOJO_MAX_MEMORY_SIZE
. -
mode
The mode to open the file with in the case a callback is used and defaulting to
<:encoding(UTF-8)
.
SEE ALSO
- Mojo::File
- Mojo::File::Role::IngestI
- Mojo::File::Role::Lines
- mojolicious/mojo#1392
- mojolicious/mojo#1478
COPYRIGHT & LICENSE
This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself.
AUTHORS
Roy Storey - kiwiroy@cpan.org