-
Notifications
You must be signed in to change notification settings - Fork 62
/
azure.rb
109 lines (90 loc) · 2.56 KB
/
azure.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
99
100
101
102
103
104
105
106
107
108
109
require 'azure'
module CarrierWave
module Storage
class Azure < Abstract
def store!(file)
azure_file = CarrierWave::Storage::Azure::File.new(uploader, connection, uploader.store_path)
azure_file.store!(file)
azure_file
end
def retrieve!(identifer)
CarrierWave::Storage::Azure::File.new(uploader, connection, uploader.store_path(identifer))
end
def connection
@connection ||= begin
%i(storage_account_name storage_access_key storage_blob_host).each do |key|
::Azure.config.send("#{key}=", uploader.send("azure_#{key}"))
end
::Azure::BlobService.new
end
end
class File
attr_reader :path
def initialize(uploader, connection, path)
@uploader = uploader
@connection = connection
@path = path
end
def store!(file)
@content = file.read
@content_type = file.content_type
@connection.create_block_blob @uploader.azure_container, @path, @content, content_type: @content_type
true
end
def url(options = {})
path = ::File.join @uploader.azure_container, @path
if @uploader.asset_host
"#{@uploader.asset_host}/#{path}"
else
@connection.generate_uri(path).to_s
end
end
def read
content
end
def content_type
@content_type = blob.properties[:content_type] if @content_type.nil? && !blob.nil?
@content_type
end
def content_type=(new_content_type)
@content_type = new_content_type
end
def exitst?
blob.nil?
end
def size
blob.properties[:content_length] unless blob.nil?
end
def filename
URI.decode(url).gsub(/.*\/(.*?$)/, '\1')
end
def extension
@path.split('.').last
end
def delete
begin
@connection.delete_blob @uploader.azure_container, @path
true
rescue ::Azure::Core::Http::HTTPError
false
end
end
private
def blob
load_content if @blob.nil?
@blob
end
def content
load_content if @content.nil?
@content
end
def load_content
@blob, @content = begin
@connection.get_blob @uploader.azure_container, @path
rescue ::Azure::Core::Http::HTTPError
end
end
end
end
end
end