| 1 | package Plagger::Plugin::Publish::Serializer; | ||
| 2 | use strict; | ||
| 3 | use base qw( Plagger::Plugin ); | ||
| 4 | |||
| 5 | use Data::Serializer; | ||
| 6 | use Plagger::Util; | ||
| 7 | use Plagger::Walker; | ||
| 8 | |||
| 9 | sub register { | ||
| 10 | my($self, $context) = @_; | ||
| 11 | $context->register_hook( | ||
| 12 | $self, | ||
| 13 | 'publish.feed' => \&feed, | ||
| 14 | 'plugin.init' => \&initialize, | ||
| 15 | ); | ||
| 16 | } | ||
| 17 | |||
| 18 | sub initialize { | ||
| 19 | my($self, $context, $args) = @_; | ||
| 20 | my $dir = $self->conf->{dir} or $context->error("dir is required"); | ||
| 21 | |||
| 22 | unless (-e $dir && -d _) { | ||
| 23 | mkdir $dir, 0755 or $context->error("mkdir $dir: $!"); | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | sub feed { | ||
| 28 | my($self, $context, $args) = @_; | ||
| 29 | |||
| 30 | my $file = Plagger::Util::filename_for($args->{feed}, $self->conf->{filename}); | ||
| 31 | my $path = File::Spec->catfile($self->conf->{dir}, $file); | ||
| 32 | |||
| 33 | my $data = $self->serialize( Plagger::Walker->serialize($args->{feed}) ); | ||
| 34 | utf8::encode($data) if utf8::is_utf8($data); | ||
| 35 | |||
| 36 | $context->log(info => "Serializing " . $args->{feed}->id . " to $path"); | ||
| 37 | open my $out, ">", $path or $context->error("$path: $!"); | ||
| 38 | print $out $data; | ||
| 39 | close $out; | ||
| 40 | } | ||
| 41 | |||
| 42 | sub serialize { | ||
| 43 | my($self, $data) = @_; | ||
| 44 | |||
| 45 | my $selializer = Data::Serializer->new( | ||
| 46 | serializer => $self->conf->{serializer} || 'Data::Dumper', | ||
| 47 | options => $self->conf->{option} || {}, | ||
| 48 | ); | ||
| 49 | |||
| 50 | $selializer->raw_serialize($data); | ||
| 51 | } | ||
| 52 | |||
| 53 | 1; | ||
| 54 | __END__ |