1 |
package WebPAC::Output::JSON; |
2 |
|
3 |
use warnings; |
4 |
use strict; |
5 |
|
6 |
use base qw/WebPAC::Common WebPAC::Output Class::Accessor/; |
7 |
__PACKAGE__->mk_accessors(qw(path)); |
8 |
|
9 |
use Data::Dump qw/dump/; |
10 |
use JSON; |
11 |
use File::Slurp; |
12 |
use autodie; |
13 |
|
14 |
=head1 NAME |
15 |
|
16 |
WebPAC::Output::JSON - Create JSON output |
17 |
|
18 |
=head1 VERSION |
19 |
|
20 |
Version 0.00 |
21 |
|
22 |
=cut |
23 |
|
24 |
our $VERSION = '0.00'; |
25 |
|
26 |
=head1 SYNOPSIS |
27 |
|
28 |
Create JSON output for export into other sistems |
29 |
|
30 |
=head1 FUNCTIONS |
31 |
|
32 |
=head2 new |
33 |
|
34 |
my $out = new WebPAC::Output::JSON({ |
35 |
path => '/path/to/file.js', |
36 |
}); |
37 |
|
38 |
Options are: |
39 |
|
40 |
=over 4 |
41 |
|
42 |
=item path |
43 |
|
44 |
path to JSON file |
45 |
|
46 |
=back |
47 |
|
48 |
=head2 init |
49 |
|
50 |
$out->init; |
51 |
|
52 |
=cut |
53 |
|
54 |
sub init { |
55 |
my $self = shift; |
56 |
my $log = $self->_get_logger; |
57 |
|
58 |
$log->debug('init'); |
59 |
|
60 |
$self->{_data} = []; |
61 |
|
62 |
return 1; |
63 |
} |
64 |
|
65 |
|
66 |
=head2 add |
67 |
|
68 |
Adds one entry to database. |
69 |
|
70 |
$out->add( 42, $ds ); |
71 |
|
72 |
=cut |
73 |
|
74 |
sub add { |
75 |
my $self = shift; |
76 |
|
77 |
my ( $id, $ds ) = @_; |
78 |
|
79 |
my $log = $self->_get_logger; |
80 |
$log->logdie("need id") unless defined $id; |
81 |
$log->logdie("need ds") unless $ds; |
82 |
|
83 |
$log->debug("id: $id ds = ",sub { dump($ds) }); |
84 |
|
85 |
push @{ $self->{_data} }, $self->ds_to_hash( $ds, 'display' ); |
86 |
|
87 |
return 1; |
88 |
} |
89 |
|
90 |
=head2 finish |
91 |
|
92 |
$out->finish; |
93 |
|
94 |
=cut |
95 |
|
96 |
sub finish { |
97 |
my $self = shift; |
98 |
|
99 |
my $log = $self->_get_logger(); |
100 |
|
101 |
if ( @{ $self->{_data} } ) { |
102 |
|
103 |
use bytes; |
104 |
|
105 |
open(my $fh, '>', $self->path); |
106 |
print $fh to_json( { items => $self->{_data} } ); |
107 |
close $fh; |
108 |
|
109 |
$log->info("wrote JSON to ", $self->path, ' ', -s $self->path, ' bytes'); |
110 |
|
111 |
} else { |
112 |
$log->error("no data for JSON generated - remove this output?"); |
113 |
} |
114 |
|
115 |
} |
116 |
|
117 |
=head1 AUTHOR |
118 |
|
119 |
Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >> |
120 |
|
121 |
=head1 COPYRIGHT & LICENSE |
122 |
|
123 |
Copyright 2007 Dobrica Pavlinusic, All Rights Reserved. |
124 |
|
125 |
This program is free software; you can redistribute it and/or modify it |
126 |
under the same terms as Perl itself. |
127 |
|
128 |
=cut |
129 |
|
130 |
1; # End of WebPAC::Output::JSON |