Skip to content

Commit ce12439

Browse files
Fix asset type detection in ActiveStorage
Fixes #555
1 parent de46088 commit ce12439

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

lib/active_storage/service/cloudinary_service.rb

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def upload(key, io, filename: nil, checksum: nil, **options)
6262
end
6363

6464
def url(key, filename: nil, content_type: '', **options)
65+
key = find_blob_or_use_key(key)
6566
instrument :url, key: key do |payload|
6667
url = Cloudinary::Utils.cloudinary_url(
6768
full_public_id_internal(key, options),
@@ -105,6 +106,7 @@ def headers_for_direct_upload(key, content_type:, checksum:, **)
105106
end
106107

107108
def delete(key)
109+
key = find_blob_or_use_key(key)
108110
instrument :delete, key: key do
109111
options = {
110112
resource_type: resource_type(nil, key),
@@ -121,6 +123,7 @@ def delete_prefixed(prefix)
121123
end
122124

123125
def exist?(key)
126+
key = find_blob_or_use_key(key)
124127
instrument :exist, key: key do |payload|
125128
begin
126129
options = {
@@ -157,8 +160,7 @@ def download(key, &block)
157160

158161
# Return the partial content in the byte +range+ of the file at the +key+.
159162
def download_chunk(key, range)
160-
url = Cloudinary::Utils.cloudinary_url(public_id(key), resource_type: resource_type(nil, key))
161-
uri = URI(url)
163+
uri = URI(url(key))
162164
instrument :download, key: key do
163165
req = Net::HTTP::Get.new(uri)
164166
range_end = case
@@ -309,5 +311,19 @@ def resource_type(io, key = "", content_type = "")
309311
end
310312
content_type_to_resource_type(content_type)
311313
end
314+
315+
def find_blob_or_use_key(key)
316+
if key.is_a?(ActiveStorage::BlobKey)
317+
key
318+
else
319+
begin
320+
blob = ActiveStorage::Blob.find_by(key: key)
321+
blob ? ActiveStorage::BlobKey.new(blob.attributes.as_json) : key
322+
rescue ActiveRecord::StatementInvalid => e
323+
# Return the original key if an error occurs
324+
key
325+
end
326+
end
327+
end
312328
end
313329
end

0 commit comments

Comments
 (0)