catlxom の Account Auto-Discovery プラグイン (catlxom メモ #9)

catlxom で RSS や TrackBack 等の Auto Discovery データを追加するためのプラグインを書こうと思い、まずは Account Auto-Discovery データを追加するプラグインを書いてみた。

blosxom でも 同様のプラグイン を書いているのですが、一番大きな違いは、blosxom プラグインはテンプレートの修正が必要なのに対し、catlxom プラグインはテンプレートの修正が一切必要ありません。XML::TreeBuilder を利用して、HTML ヘッダにデータを追加するような作りにしています。

利用上の注意点として、Template::TT よりも後にこのプラグインをロードしなければいけいのですが、自動ロードを有効にしてると先にロードされちゃうので、自動ロードをオフにして yaml で明示的に利用プラグインを指定する必要があります。

package Catlxom::Plugin::Format::AccountAutoDiscovery;
use strict;
use warnings;
use base qw/Catlxom::Plugin/;

use NEXT;
use XML::TreeBuilder;

sub interpolate {
    my ( $self, $c ) = @_;

    my $accounts = $c->config->{account_auto_discovery};

    my $tree = XML::TreeBuilder->new();
    $tree->parse($c->res->body);

    my $head = $tree->find('head');

    for ( @$accounts ){
        my $rdf = XML::Element->new(
            'rdf:RDF',
            'xmlns:rdf'  => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
            'xmlns:foaf' => 'http://xmlns.com/foaf/0.1/',
        );

        my $rdf_description = XML::Element->new(
            'rdf:Description',
            'rdf:about' => $c->req->uri,
        );

        my $foaf_maker = XML::Element->new(
            'foaf:maker',
            'rdf:parseType' => 'Resource',
        );

        my $foaf_holds_acount = XML::Element->new( 'foaf:holdsAccount' );

        my $foaf_online_account = XML::Element->new(
            'foaf:OnlineAccount',
            'foaf:accountName' => $_->{account_name},
        );

        my $foaf_account_service_homepage = XML::Element->new(
            'foaf:accountServiceHomepage',
            'rdf:resource' => $_->{account_service_homepage},
        );

        $head->push_content($rdf);
        $rdf->push_content($rdf_description);
        $rdf_description->push_content($foaf_maker);
        $foaf_maker->push_content($foaf_holds_acount);
        $foaf_holds_acount->push_content($foaf_online_account);
        $foaf_online_account->push_content($foaf_account_service_homepage);
    }

    $c->res->{body} = $tree->as_HTML;
    $self->NEXT::interpolate($c);
}

1;

__END__

=head1 NAME

Catlxom::Plugin::Format::AccountAutoDiscovery

=head1 SYNOPSIS

account_auto_discovery:
  - account_name: gosukenator
    account_service_homepage: http://www.hatena.ne.jp/
  - account_name: xxxx
    account_service_homepage: http://xxx.ne.jp/

=head1 DESCRIPTION

This plugin inserts Account Auto-Discovery data into HTML header.

=head1 AUTHOR

Gosuke Miyashita

=head1 SEE ALSO

L<http://b.hatena.ne.jp/help?mode=tipjar#autodiscovery>

=cut