summaryrefslogtreecommitdiffstats
path: root/lib/Spreadsheet/Template/Helpers/Xslate.pm
blob: c49cfa9db750dd81e58435c89377106ffdfa48e7 (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
package Spreadsheet::Template::Helpers::Xslate;
use strict;
use warnings;
use Data::Dumper;

use JSON;

my $JSON = JSON->new;

use Sub::Exporter 'build_exporter';

my $import = build_exporter({
    exports => [
        map { $_ => \&_curry_package } qw(format c merge true false)
    ],
    groups => {
        default => [qw(format c merge true false)],
    },
});

my %formats;

sub import {
    my $caller = caller;
    $formats{$caller} = {};
    goto $import;
}

sub format {
    my ($package, $name, $format) = @_;
    $formats{$package}{$name} = $format;
    return '';
}

sub merge {
    my ($package, $range, $contents, $format) = @_;

    return $JSON->encode({
        range    => "$range",
        contents => "$contents",
        format   => _formats($package, $format)
    });
}

sub c {
    my ($package, $contents, $format, $type, %args) = @_;

    $type = 'string' unless defined $type;

    return $JSON->encode({
        contents => "$contents",
        format   => _formats($package, $format),
        type     => $type,
        (defined $args{formula}
            ? (formula => $args{formula})
            : ()),
    });
}

sub true  { JSON::true  }
sub false { JSON::false }

sub _formats {
    my ($package, $format) = @_;

    return $format if ref($format);

    return $formats{$package}{$format};
}

sub _curry_package {
    my ($package, $name) = @_;
    return sub { $package->$name(@_) };
}

=begin Pod::Coverage

 format
 c
 true
 false

=end Pod::Coverage

=cut

1;