package TableDataRole::AsCSV;

our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
our $DATE = '2021-04-11'; # DATE
our $DIST = 'TableData'; # DIST
our $VERSION = '0.1.4'; # VERSION

use 5.010001;
use strict;
use warnings;

use Role::Tiny;

sub as_csv {
    state $csv = do {
        require Text::CSV;
        Text::CSV->new({ binary=>1, auto_diag=>1 });
    };

    my $table = shift;

    my $res = "";
    $table->reset_row_iterator;
    $csv->combine( $table->get_column_names ); # XXX check status?
    $res .= $csv->string . "\n";
    while (defined(my $row = $table->get_row_arrayref)) {
        $csv->combine(@$row); # XXX check status
        $res .= $csv->string . "\n";
    }
    $res;
}

1;
# ABSTRACT: Provide as_csv() method

__END__

=pod

=encoding UTF-8

=head1 NAME

TableDataRole::AsCSV - Provide as_csv() method

=head1 VERSION

This document describes version 0.1.4 of TableDataRole::AsCSV (from Perl distribution TableData), released on 2021-04-11.

=head2 as_csv

Usage:

 my $csv = $table->as_csv;

Return the whole table data as CSV (string). Will reset the row iterator.

This implementation will call L</reset_row_iterator>, call L</get_row_arrayref>
repeatedly, format the rows as CSV and return it. If your source data is already
in CSV format, you can simply return the CSV data instead.

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/TableData>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-Tables>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=TableData>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2021, 2020 by perlancar@cpan.org.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
