| File: | lib/Bot/IRC/Store.pm |
| Coverage: | 91.5% |
| line | stmt | bran | cond | sub | pod | time | code |
|---|---|---|---|---|---|---|---|
| 1 | package Bot::IRC::Store; | ||||||
| 2 | # ABSTRACT: Bot::IRC Persistent Data Storage with YAML | ||||||
| 3 | |||||||
| 4 | 2 2 2 | 37 26 92 | use strict; | ||||
| 5 | 2 2 2 | 46 20 125 | use warnings; | ||||
| 6 | |||||||
| 7 | 2 2 2 | 1248 34311 1288 | use YAML::XS qw( LoadFile DumpFile ); | ||||
| 8 | |||||||
| 9 | # VERSION | ||||||
| 10 | |||||||
| 11 | sub init { | ||||||
| 12 | 2 | 0 | 13 | my ($bot) = @_; | |||
| 13 | 2 | 15 | my $obj = __PACKAGE__->new($bot); | ||||
| 14 | |||||||
| 15 | 2 4 | 44 37 | $bot->subs( 'store' => sub { return $obj } ); | ||||
| 16 | } | ||||||
| 17 | |||||||
| 18 | sub new { | ||||||
| 19 | 3 | 0 | 42 | my ( $class, $bot ) = @_; | |||
| 20 | 3 | 18 | my $self = bless( {}, $class ); | ||||
| 21 | |||||||
| 22 | 3 | 41 | $self->{file} = $bot->{vars}{store} || 'store.yaml'; | ||||
| 23 | |||||||
| 24 | 3 | 16 | eval { | ||||
| 25 | 3 | 138 | unless ( -f $self->{file} ) { | ||||
| 26 | 1 | 12 | DumpFile( $self->{file}, {} ); | ||||
| 27 | } | ||||||
| 28 | else { | ||||||
| 29 | 2 | 14 | LoadFile( $self->{file} ); | ||||
| 30 | } | ||||||
| 31 | }; | ||||||
| 32 | 3 | 7204 | die qq{Unable to use "$self->{file}" for YAML storage in the Bot::IRC::Store plugin\n} if ($@); | ||||
| 33 | |||||||
| 34 | 3 | 25 | return $self; | ||||
| 35 | } | ||||||
| 36 | |||||||
| 37 | sub get { | ||||||
| 38 | 1 | 1 | 5 | my ( $self, $key ) = @_; | |||
| 39 | 1 | 7 | return LoadFile( $self->{file} )->{ ( caller() )[0] }{$key}; | ||||
| 40 | } | ||||||
| 41 | |||||||
| 42 | sub set { | ||||||
| 43 | 1 | 1 | 5 | my ( $self, $key, $value ) = @_; | |||
| 44 | |||||||
| 45 | 1 | 7 | my $data = LoadFile( $self->{file} ); | ||||
| 46 | 1 | 8 | $data->{ ( caller() )[0] }{$key} = $value; | ||||
| 47 | |||||||
| 48 | 1 | 39 | DumpFile( $self->{file}, $data ); | ||||
| 49 | 1 | 9 | return $self; | ||||
| 50 | } | ||||||
| 51 | |||||||
| 52 | 1; | ||||||