move to github
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / IO / StorableFile.pm
1 package MooseX::Storage::IO::StorableFile;
2 use Moose::Role;
3
4 use Storable ();
5
6 requires 'pack';
7 requires 'unpack';
8
9 sub load {
10     my ( $class, $filename, @args ) = @_;
11     # try thawing
12     return $class->thaw( Storable::retrieve($filename), @args )
13         if $class->can('thaw');
14     # otherwise just unpack
15     $class->unpack( Storable::retrieve($filename), @args );
16 }
17
18 sub store {
19     my ( $self, $filename, @args ) = @_;
20     Storable::nstore(
21         # try freezing, otherwise just pack
22         ($self->can('freeze') ? $self->freeze(@args) : $self->pack(@args)),
23         $filename
24     );
25 }
26
27 no Moose::Role;
28
29 1;
30
31 __END__
32
33 =pod
34
35 =head1 NAME
36
37 MooseX::Storage::IO::StorableFile - An Storable File I/O role
38
39 =head1 SYNOPSIS
40
41   package Point;
42   use Moose;
43   use MooseX::Storage;
44
45   with Storage('io' => 'StorableFile');
46
47   has 'x' => (is => 'rw', isa => 'Int');
48   has 'y' => (is => 'rw', isa => 'Int');
49
50   1;
51
52   my $p = Point->new(x => 10, y => 10);
53
54   ## methods to load/store a class
55   ## on the file system
56
57   $p->store('my_point');
58
59   my $p2 = Point->load('my_point');
60
61 =head1 DESCRIPTION
62
63 This module will C<load> and C<store> Moose classes using Storable. It
64 uses C<Storable::nstore> by default so that it can be easily used
65 across machines or just locally.
66
67 One important thing to note is that this module does not mix well
68 with the other Format modules. Since Storable serialized perl data
69 structures in it's own format, those roles are largely unnecessary.
70
71 However, there is always the possibility that having a set of
72 C<freeze/thaw> hooks can be useful, so because of that this module
73 will attempt to use C<freeze> or C<thaw> if that method is available.
74 Of course, you should be careful when doing this as it could lead to
75 all sorts of hairy issues. But you have been warned.
76
77 =head1 METHODS
78
79 =over 4
80
81 =item B<load ($filename)>
82
83 =item B<store ($filename)>
84
85 =back
86
87 =head2 Introspection
88
89 =over 4
90
91 =item B<meta>
92
93 =back
94
95 =head1 BUGS
96
97 All complex software has bugs lurking in it, and this module is no
98 exception. If you find a bug please either email me, or add the bug
99 to cpan-RT.
100
101 =head1 AUTHOR
102
103 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
104
105 =head1 COPYRIGHT AND LICENSE
106
107 Copyright 2007-2008 by Infinity Interactive, Inc.
108
109 L<http://www.iinteractive.com>
110
111 This library is free software; you can redistribute it and/or modify
112 it under the same terms as Perl itself.
113
114 =cut
115
116