-
Notifications
You must be signed in to change notification settings - Fork 1
/
s3_uploader.rb
66 lines (57 loc) · 1.47 KB
/
s3_uploader.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
require "fog"
require "active_support/core_ext"
class S3Uploader
attr_accessor :path
attr_accessor :authorization
def initialize(authorization, path)
self.authorization = authorization
self.path = path
end
def processed_path(file_name)
"#{path}/#{File.basename(file_name)}"
end
def storage
@storage ||= Fog::Storage.new(
:provider => 'AWS',
:aws_access_key_id => authorization[:key],
:aws_secret_access_key => authorization[:secret],
:region => authorization[:region],
:persistent => false
)
end
def directory
@directory ||= (
storage.directories.get(authorization[:bucket]) ||
storage.directories.create(
:key => authorization[:bucket]
)
)
end
def destroy(file_path)
directory.files.get(file_path).try(:destroy)
end
def upload(file_name, path=nil)
if File.directory? file_name
upload_dir(file_name, path)
else
file = directory.files.create(
:key => path || processed_path(file_name),
:body => File.open(file_name),
:public => true
)
end
end
def upload_dir(dir, path=nil)
Dir["#{dir}/**/*"].each do |inner_file|
upload(inner_file, (path == nil) ? inner_file : "#{path}/#{inner_file}")
end
end
def self.instance(key=nil, secret=nil, bucket=nil, region=nil)
@instance ||= S3Uploader.new({
:key => key,
:secret => secret,
:bucket => bucket,
:region => region
}, "")
end
end