basic show works
[scpubgit/Commentry.git] / lib / App / Commentry.pm
1 package App::Commentry;
2
3 use aliased 'App::Commentry::CommentStore';
4 use FindBin;
5 use HTML::Zoom;
6 use Web::Simple;
7
8 sub default_config {
9   (
10     store_dir => $FindBin::Bin.'/../store/comments',
11     template_dir => $FindBin::Bin.'/../share/html',
12   )
13 }
14
15 has comment_store => (
16   is => 'lazy', handles => { 'comments_for' => 'get' }
17 );
18
19 sub _build_comment_store {
20   my $self = shift;
21   my $store_dir = $self->config->{store_dir};
22   die "Comment Store directory ${store_dir} does not exist"
23     unless -d $store_dir;
24   CommentStore->new(base_dir => $self->config->{store_dir});
25 }
26
27 has template_dir => (
28   is => 'lazy'
29 );
30
31 sub _build_template_dir {
32   my $self = shift;
33   my $template_dir = $self->config->{template_dir};
34   die "template_dir ${template_dir} does not exist"
35     unless -d $template_dir;
36   $template_dir;
37 }
38
39 sub dispatch_request {
40   my ($self) = @_;
41   sub (/fragments/*/**) {
42     my ($self, $action, $path) = @_;
43     return unless $action eq 'show' or $action eq 'add';
44     return unless my $set = $self->comments_for({ path => $path });
45     $self->${\"_fragment_${action}"}($set);
46   }
47 }
48
49 sub _fragment_show {
50   my ($self, $set) = @_;
51   sub (GET) {
52     $self->_zoom_response(fragment_show => sub {
53       $_->select('.comment')
54         ->repeat($set->map(sub {
55             my ($comment) = @_;
56             sub {
57               $_->select('.comment-title')->replace_content($comment->title)
58                 ->select('.comment-body')->replace_content($comment->body)
59             }
60           }));
61     });
62   }
63 }
64
65 sub _zoom_response {
66   my ($self, $template, $apply) = @_;
67   my $zfh = ($self->{zoom_cache}{$template} ||= do {
68     HTML::Zoom->from_file($self->template_dir.'/'.$template.'.html')
69   })->apply($apply)->to_fh;
70   [ 200, [ 'Content-type' => 'text/html' ], $zfh ];
71 }
72
73 1;