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

Revision 1389 (checked in by miyagawa, 14 years ago)

Added Publish::Serializer via http://naoya.g.hatena.ne.jp/naoya/20060315/1142433649

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}));
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     $context->log(info => "Serializing " . $args->{feed}->id . " to $path");
34
35     open my $out, ">:utf8", $path or $context->error("$path: $!");
36     print $out $body;
37     close $out;
38 }
39
40 1;
41
42 __END__
43
44 =head1 NAME
45
46 Plagger::Plugin::Publish::JSON - Publish JSON data output
47
48 =head1 SYNOPSIS
49
50   - module: Publish::JSON
51     config:
52       dir: /path/to/data
53
54 =head1 DESCRIPTION
55
56 This plugin dumps feed data to JSON JavaScript Object Notation.
57
58 =head1 CONFIG
59
60 =over 4
61
62 =item dir
63
64 Directory name to save.
65
66 =item varname
67
68   varname: foo
69
70 Variable name to store JSON data. If set, .json file would include the
71 variable declaration e.g.:
72
73   var foo = { ... }
74
75 Optional.
76
77 =item jsonp
78
79   jsonp: bar
80
81 JSONP callback name to pass JSON data back. Optional. If set, .json
82 file would wrap the returned data in a callback function, e.g.:
83
84   bar({ ... })
85
86 Optional.
87
88 =back
89
90 =head1 AUTHOR
91
92 Tatsuhiko Miyagawa
93
94 =head1 SEE ALSO
95
96 L<Plagger>, L<JSON::Syck>
97
98 =cut
Note: See TracBrowser for help on using the browser.