summaryrefslogtreecommitdiffstats
path: root/lib/Spreadsheet/Template/Generator.pm
blob: 79282d799a2e5ab22cd4b585e8020576b192486d (plain) (blame)
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
package Spreadsheet::Template::Generator;
use Moose;
# ABSTRACT: create new templates from existing spreadsheets

use Class::Load 'load_class';
use JSON;

=head1 SYNOPSIS

  use Spreadsheet::Template::Generator;

  my $generator = Spreadsheet::Template::Generator->new;
  open my $fh, '>:encoding(utf8)', 'out.json';
  $fh->print($generator->generate($filename));

=head1 DESCRIPTION

This module is used to create new templates from existing spreadsheets. You can
then modify this output to be suitable to use as input for
L<Spreadsheet::Template> by, for instance, adding in L<Text::Xslate> directives
to use your actual data, rather than the hardcoded data in the original
spreadsheet.

=cut

=attr parser_class

The class to use for parsing the spreadsheet. Defaults to
L<Spreadsheet::Template::Generator::Parser::XLSX>.

=cut

has parser_class => (
    is      => 'ro',
    isa     => 'Str',
    default => 'Spreadsheet::Template::Generator::Parser::XLSX',
);

=attr parser_options

Options to pass to the parser constructor. Defaults to an empty hashref.

=cut

has parser_options => (
    is      => 'ro',
    isa     => 'HashRef',
    default => sub { {} },
);

=attr parser

The L<Spreadsheet::Template::Generator::Parser> instance that will be used.

=cut

has parser => (
    is   => 'ro',
    does => 'Spreadsheet::Template::Generator::Parser',
    lazy => 1,
    default => sub {
        my $self = shift;
        my $class = $self->parser_class;
        load_class($class);
        return $class->new(
            %{ $self->parser_options }
        );
    },
);

=method generate($filename)

Returns a string containing the JSON representation of the data contained in
the spreadsheet file C<$filename>. This representation is documented in
L<Spreadsheet::Template>.

=cut

sub generate {
    my $self = shift;
    my ($filename) = @_;
    my $data = $self->parser->parse($filename);
    return JSON->new->pretty->canonical->encode($data);
}

__PACKAGE__->meta->make_immutable;
no Moose;

1;