This repository has been archived by the owner on Jul 13, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
fog.rb
98 lines (85 loc) · 2.58 KB
/
fog.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
91
92
93
94
95
96
97
98
module Paperclip
module Storage
module Fog
def self.extended base
begin
require 'fog'
rescue LoadError => e
e.message << " (You may need to install the fog gem)"
raise e
end unless defined?(Fog)
base.instance_eval do
@fog_directory = @options[:fog_directory]
@fog_credentials = @options[:fog_credentials]
@fog_host = @options[:fog_host]
@fog_public = @options[:fog_public]
@url = ':fog_public_url'
Paperclip.interpolates(:fog_public_url) do |attachment, style|
attachment.public_url(style)
end unless Paperclip::Interpolations.respond_to? :fog_public_url
end
end
def exists?(style = default_style)
if original_filename
!!directory.files.head(path(style))
else
false
end
end
def flush_writes
for style, file in @queued_for_write do
log("saving #{path(style)}")
directory.files.create(
:body => file,
:key => path(style),
:public => @fog_public
)
end
@queued_for_write = {}
end
def flush_deletes
for path in @queued_for_delete do
log("deleting #{path}")
directory.files.new(:key => path).destroy
end
@queued_for_delete = []
end
# Returns representation of the data of the file assigned to the given
# style, in the format most representative of the current storage.
def to_file(style = default_style)
if @queued_for_write[style]
@queued_for_write[style]
else
body = directory.files.get(path(style)).body
filename = path(style)
extname = File.extname(filename)
basename = File.basename(filename, extname)
file = Tempfile.new([basename, extname])
file.binmode
file.write(body)
file.rewind
file
end
end
def public_url(style = default_style)
if @fog_host
"#{@fog_host}/#{path(style)}"
else
directory.files.new(:key => path(style)).public_url
end
end
private
def connection
@connection ||= ::Fog::Storage.new(@fog_credentials)
end
def directory
@directory ||= begin
connection.directories.get(@fog_directory) || connection.directories.create(
:key => @fog_directory,
:public => @fog_public
)
end
end
end
end
end