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