1 |
# Dobrica Pavlinusic, <dpavlin@rot13.org> 10/26/07 21:37:12 CEST |
2 |
package CWMP::Store::YAML; |
3 |
|
4 |
use strict; |
5 |
use warnings; |
6 |
|
7 |
use Data::Dump qw/dump/; |
8 |
use YAML qw/LoadFile DumpFile/; |
9 |
use Hash::Merge qw/merge/; |
10 |
|
11 |
=head1 NAME |
12 |
|
13 |
CWMP::Store::YAML - use YAML as storage |
14 |
|
15 |
=head1 METHODS |
16 |
|
17 |
=head2 open |
18 |
|
19 |
=cut |
20 |
|
21 |
my $dir = 'yaml'; |
22 |
|
23 |
my $debug = 1; |
24 |
|
25 |
sub open { |
26 |
my $self = shift; |
27 |
|
28 |
warn "open ",dump( @_ ); |
29 |
|
30 |
if ( ! -e $dir ) { |
31 |
mkdir $dir || die "can't create $dir: $!"; |
32 |
warn "created $dir directory\n"; |
33 |
} |
34 |
|
35 |
} |
36 |
|
37 |
=head2 update_uid_state |
38 |
|
39 |
$store->update_uid_state( $uid, $state ); |
40 |
|
41 |
=cut |
42 |
|
43 |
sub update_uid_state { |
44 |
my ( $self, $uid, $state ) = @_; |
45 |
|
46 |
my $file = "$dir/$uid.yml"; |
47 |
|
48 |
my $old_state = $self->get_state( $uid ); |
49 |
|
50 |
my $combined = merge( $state, $old_state ); |
51 |
|
52 |
# warn "## ",dump( $old_state, $state, $combined ); |
53 |
|
54 |
DumpFile( $file, $combined ) || die "can't write $file: $!"; |
55 |
|
56 |
} |
57 |
|
58 |
=head2 get_state |
59 |
|
60 |
$store->get_state( $uid ); |
61 |
|
62 |
=cut |
63 |
|
64 |
sub get_state { |
65 |
my ( $self, $uid ) = @_; |
66 |
|
67 |
my $file = "$dir/$uid.yml"; |
68 |
|
69 |
if ( -e $file ) { |
70 |
return LoadFile( $file ); |
71 |
} |
72 |
|
73 |
return; |
74 |
} |
75 |
|
76 |
=head2 all_uids |
77 |
|
78 |
my @uids = $store->all_uids; |
79 |
|
80 |
=cut |
81 |
|
82 |
sub all_uids { |
83 |
my $self = shift; |
84 |
|
85 |
opendir(my $d, $dir) || die "can't opendir $dir: $!"; |
86 |
my @uids = grep { /\.yml$/ && -f "$dir/$_" } readdir($d); |
87 |
closedir $d; |
88 |
|
89 |
return map { my $l = $_; $l =~ s/\.yml$//; $l } @uids; |
90 |
} |
91 |
|
92 |
1; |