summaryrefslogtreecommitdiff
path: root/lib/DeWeave/Collection.pm
blob: 3fe08e3c3407f6306d6b3e119a8a8cb30bd78539 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package DeWeave::Collection; 
use Moose;
use namespace::autoclean;
use MooseX::Types::Moose qw(ArrayRef);
use JSON::Any;
use Try::Tiny;
use DeWeave::EDO;
use Lingua::EN::Inflect::Number 'to_S';
use Log::Log4perl ':easy';
use Data::Dump 'pp';
 
has items => (
    isa => ArrayRef['DeWeave::WBO'],
    is => 'ro',
    required => 1,
);
 
sub _local_part {
    my ($class) = @_;
    my ($sub) = ($class =~ m{^DeWeave::Collection::(\w+)});
    return $sub;
}
 
sub item_class {
    my ($class) = @_;
    my $sub = ucfirst(to_S(lc($class->_local_part)));
    return "DeWeave::BO::$sub" if $sub;
    return 'DeWeave::WBO'
}
 
sub items_path {
    my ($class) = @_;
    my $sub = lc($class->_local_part);
    return "storage/$sub";
}
 
sub from_json {
    my ($class,$json,$crypt)=@_;
 
    my $j = JSON::Any->new;
 
    my $args = $j->decode($json);
 
DEBUG '$args ',{filter=>\&pp,value=>$args};
 
    my @items;my %deletions;
 
    for my $input_item (@$args) {
        my $item_args = DeWeave::WBO->unpack_args($input_item,$crypt);
 
        if (exists $item_args->{deleted}) {
            $deletions{$item_args->{id}}=undef;
            next;
        }
 
        # the $item_args is passed to allow subclasses to 
        # generate objects of different types for different inputs 
        my $item = $class->item_class($item_args)
                ->new($item_args);
 
        push @items,$item
            if $item;
    }
 
    @items = grep { ! exists $deletions{$_->id} } @items;
 
    return $class->new({
        items => \@items,
    });
}
 
sub fetch {
    my ($class,$storage,$crypto) = @_;
 
    my $path = $class->items_path;
    my $data = $storage->get_item($path);
 
    return $class->from_json(
        $data,
        $crypto,
    );
}
 
1;
 
__END__
 
=head1 AUTHOR
 
Gianni Ceccarelli <dakkar@thenautilus.net>
 
=head1 COPYRIGHT AND LICENSE
 
This software is copyright (c) 2012 by Gianni Ceccarelli.
 
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, version 3.
 
=cut