summaryrefslogtreecommitdiff
path: root/lib/DeWeave/Collection.pm
blob: 92c53428829535ffe18a4b41af7bd7b8c6d2e50b (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
package DeWeave::Collection; 
use Moose;
use namespace::autoclean;
use MooseX::Types::Moose qw(ArrayRef);
use JSON::Any;
use DeWeave::EDO;
use Lingua::EN::Inflect::Number 'to_S';
 
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);
 
    my @items = map {
        $class->item_class->new({%$_,__crypt=>$crypt})
      @$args;
    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;