-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
local_file.rb
90 lines (77 loc) · 2.37 KB
/
local_file.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
module FileStorage
# Store and retrieve files from the local filesystem.
class LocalFile
# Creates a new LocalFile store.
# +path+ Specifies the directory in which to store files. If not specified,
# files will be stored in a random-named temporary directory.
# +tag+ Controls naming of temporary directories. If specified, temporary
# directory names will be prefixed with this.
def initialize(path: nil, tag: 'storage')
@directory = path
@tag = tag
@ensured = false
end
def directory
@directory ||= Dir.mktmpdir "web-monitoring-db--#{@tag}"
end
def get_metadata(path)
get_metadata!(path)
# FIXME: should have a more specific error class than ArgumentError here;
# we could catch errors we don't want to.
rescue Errno::ENOENT, ArgumentError
nil
end
def get_metadata!(path)
data = File.stat(normalize_full_path(path))
{
last_modified: data.mtime,
size: data.size,
content_type: nil
}
end
def get_file(path)
File.read(normalize_full_path(path))
end
def save_file(path, content, _options = nil)
ensure_directory
File.open(full_path(path), 'wb') do |file|
content_string = content.try(:read) || content
file.write(content_string)
end
end
def url_for_file(path)
"file://#{full_path(path)}"
end
def contains_url?(url_string)
get_metadata(url_string).present?
end
private
def full_path(path)
File.join(directory, path)
end
# Normalize a file URI or path to an absolute path to the file.
# If the path specifies a directory outside this storage area, this raises
# ArgumentError.
def normalize_full_path(path)
# If it's a file URL, extract the path
path = path[7..-1] if path.starts_with? 'file://'
# If it's absolute, make sure it's in this storage's directory
if path.starts_with?('/')
unless path.starts_with?(File.join(directory, ''))
# FIXME: raise a more specific error type!
raise ArgumentError, "The path '#{path}' does not belong to this storage object"
end
path
else
full_path(path)
end
end
def ensure_directory
unless @ensured
@ensured = true
FileUtils.mkdir_p directory
end
directory
end
end
end