more correctly restore path with external file
[dbsrgits/DBIx-Class-Fixtures.git] / lib / DBIx / Class / Fixtures / External / File.pm
1 package DBIx::Class::Fixtures::External::File;
2
3 use strict;
4 use warnings;
5
6 use File::Spec::Functions 'catfile', 'splitpath';
7 use File::Path 'mkpath';
8
9 sub _load {
10   my ($class, $path) = @_;
11   open(my $fh, '<', $path)
12     || die "can't open $path: $!";
13   local $/ = undef;
14   my $content = <$fh>;
15 }
16
17 sub _save {
18   my ($class, $path, $content) = @_;
19   open (my $fh, '>', $path)
20     || die "can't open $path: $!";
21   print $fh $content;
22   close($fh);
23 }
24
25 sub backup {
26   my ($class, $key, $args) = @_;
27   my $path = catfile($args->{path}, $key);
28   return $class->_load($path);
29 }
30
31 sub restore {
32   my ($class, $key, $content, $args) = @_;
33   my ($vol, $directory, $file) = splitpath catfile($args->{path}, $key);
34   mkpath($directory) unless -d $directory;
35   my $path = catfile($vol, $directory, $file);
36   $class->_save($path, $content);
37 }
38
39 1;
40
41 =head1 NAME
42
43 DBIx::Class::Fixtures::External::File - save and restore external data
44
45 =head1 SYNOPSIS
46
47     my $fixtures = DBIx::Class::Fixtures
48       ->new({
49         config_dir => 't/var/configs',
50         config_attrs => { photo_dir => './t/var/files' });
51
52     {
53         "sets": [{
54             "class": "Photo",
55             "quantity": "all",
56             "external": {
57                 "file": {
58                     "class": "File",
59                     "args": {"path":"__ATTR(photo_dir)__"}
60                 }
61             }
62         }]
63     }
64
65 =head1 DESCRIPTION
66
67 Sometimes your database fields are pointers to external data.  The classic
68 example is you are using L<DBIx::Class::InflateColumn::FS> to manage blob
69 data.  In these cases it may be desirable to backup and restore the external
70 data via fixtures.
71
72 This module performs this function and can also serve as an example for your
73 possible custom needs.
74
75 =head1 METHODS
76
77 This module defines the following methods
78
79 =head2 backup
80
81 Accepts: Value of Database Field, $args
82
83 Given the value of a database field (which is some sort of pointer to the location
84 of an actual file, and a hashref of args (passed in the args key of your config
85 set), slurp up the file and return to to be saved in the fixure.
86
87 =head2 restore
88
89 Accepts: Value of Database Field, Content, $args
90
91 Given the value of a database field, some blob content and $args, restore the
92 file to the filesystem
93
94 =head1 AUTHOR
95
96     See L<DBIx::Class::Fixtures> for author information.
97
98 =head1 CONTRIBUTORS
99
100     See L<DBIx::Class::Fixtures> for contributor information.
101
102 =head1 LICENSE
103
104     See L<DBIx::Class::Fixtures> for license information.
105
106 =cut
107