skip damaged posts
[engit/Iron-Munger.git] / lib / IronMunger / PlaggerLoader.pm
1 use MooseX::Declare;
2
3 class IronMunger::PlaggerLoader {
4
5   use MooseX::Types::Path::Class qw(Dir);
6   use MooseX::Types::Moose qw(HashRef);
7   use Moose::Util::TypeConstraints qw(class_type);
8
9   BEGIN { class_type 'IO::All::File'; }
10
11   use IronMunger::CSVUtils qw(:all);
12
13   use aliased 'IronMunger::Post';
14   use aliased 'IronMunger::Monger';
15
16   use IO::All;
17   use Text::CSV_XS;
18
19   has dir => (is => 'ro', isa => Dir, required => 1, coerce => 1);
20
21   method _target_files () {
22     grep $_->name =~ /\.csv$/, io($self->dir)->all_files;
23   }
24
25   method _expand_post (HashRef $post_spec) {
26     Post->new($post_spec);
27   }
28
29   method _expand_posts_from_file(IO::All::File $file) {
30     return [
31       map $self->_expand_post($_),
32         @{$self->_expand_postspecs_from_file($file)},
33     ];
34   }
35
36   method _csv_column_order () {
37     my $x;
38     return map +($_ => $x++), qw(author title url at);
39   }
40
41   method _expand_postspecs_from_file(IO::All::File $file) {
42     my $csv = Text::CSV_XS->new;
43     my $io = $file->open;
44     my @post_specs;
45     my %col_order = $self->_csv_column_order;
46     while (my $post_raw = $csv->getline($io)) {
47       my %post_spec;
48       @post_spec{qw{url at}} = @{$post_raw}[@col_order{qw{url at}}];
49       next unless $post_spec{url} && $post_spec{at};
50       push(@post_specs, \%post_spec);
51     }
52     return \@post_specs;
53   }
54
55   method _expand_monger (IO::All::File $file) {
56     my ($name, $nick) = filename_to_name_and_nick(($file->splitpath)[-1]);
57     Monger->new(
58       (defined $name ? (name => $name) : ()),
59       (defined $nick ? (nick => $nick) : ()),
60       posts => $self->_expand_posts_from_file($file),
61     );
62   }
63
64   method mongers () {
65     map $self->_expand_monger($_), $self->_target_files;
66   }
67 }
68
69 1;