root/trunk/plagger/lib/Plagger/Plugin/Publish/JSON.pm

Revision 1386 (checked in by miyagawa, 14 years ago)
  • Add Publish::JSON
  • Add Plagger::Walker to get serialized data
Line 
1 package Plagger::Plugin::Publish::JSON;
2 use strict;
3 use base qw( Plagger::Plugin::Publish::JavaScript );
4
5 use File::Spec;
6 use JSON::Syck;
7 use Plagger::Walker;
8
9 sub register {
10     my($self, $context) = @_;
11     $context->register_hook(
12         $self,
13         'publish.feed' => \&feed,
14     );
15 }
16
17 sub feed {
18     my($self, $context, $args) = @_;
19
20     my $file = $self->gen_filename($args->{feed}, $self->conf->{filename} || '%i.json');
21     my $path = File::Spec->catfile($self->conf->{dir}, $file);
22     $context->log(info => "writing output to $path");
23
24     local $JSON::Syck::ImplicitUnicode = 1;
25     my $body = JSON::Syck::Dump(Plagger::Walker->serialize($args->{feed}->clone));
26
27     if (my $var = $self->conf->{varname}) {
28         $body = "var $var = $body;";
29     } elsif (my $jsonp = $self->conf->{jsonp}) {
30         $body = "$jsonp($body)";
31     }
32
33     open my $out, ">:utf8", $path or $context->error("$path: $!");
34     print $out $body;
35     close $out;
36 }
37
38 1;
39
40 __END__
41
42 =head1 NAME
43
44 Plagger::Plugin::Publish::JSON - Publish JSON data output
45
46 =head1 SYNOPSIS
47
48   - module: Publish::JSON
49     config:
50       dir: /path/to/data
51
52 =head1 DESCRIPTION
53
54 This plugin dumps feed data to JSON JavaScript Object Notation.
55
56 =head1 CONFIG
57
58 =over 4
59
60 =item dir
61
62 Directory name to save.
63
64 =item varname
65
66   varname: foo
67
68 Variable name to store JSON data. If set, .json file would include the
69 variable declaration e.g.:
70
71   var foo = { ... }
72
73 Optional.
74
75 =item jsonp
76
77   jsonp: bar
78
79 JSONP callback name to pass JSON data back. Optional. If set, .json
80 file would wrap the returned data in a callback function, e.g.:
81
82   bar({ ... })
83
84 Optional.
85
86 =back
87
88 =head1 AUTHOR
89
90 Tatsuhiko Miyagawa
91
92 =head1 SEE ALSO
93
94 L<Plagger>, L<JSON::Syck>
95
96 =cut
Note: See TracBrowser for help on using the browser.