From 78ec9674babd6200237dae1286fdf6ec7fb6ce8c Mon Sep 17 00:00:00 2001 From: Constantine Nathanson Date: Mon, 9 Sep 2024 01:21:09 +0300 Subject: [PATCH] Fix asset type detection in ActiveStorage Fixes #555 --- .../service/cloudinary_service.rb | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/active_storage/service/cloudinary_service.rb b/lib/active_storage/service/cloudinary_service.rb index 33d85c0d..0cf3d0ce 100644 --- a/lib/active_storage/service/cloudinary_service.rb +++ b/lib/active_storage/service/cloudinary_service.rb @@ -62,6 +62,7 @@ def upload(key, io, filename: nil, checksum: nil, **options) end def url(key, filename: nil, content_type: '', **options) + key = find_blob_or_use_key(key) instrument :url, key: key do |payload| url = Cloudinary::Utils.cloudinary_url( full_public_id_internal(key, options), @@ -105,6 +106,7 @@ def headers_for_direct_upload(key, content_type:, checksum:, **) end def delete(key) + key = find_blob_or_use_key(key) instrument :delete, key: key do options = { resource_type: resource_type(nil, key), @@ -121,6 +123,7 @@ def delete_prefixed(prefix) end def exist?(key) + key = find_blob_or_use_key(key) instrument :exist, key: key do |payload| begin options = { @@ -157,8 +160,7 @@ def download(key, &block) # Return the partial content in the byte +range+ of the file at the +key+. def download_chunk(key, range) - url = Cloudinary::Utils.cloudinary_url(public_id(key), resource_type: resource_type(nil, key)) - uri = URI(url) + uri = URI(url(key)) instrument :download, key: key do req = Net::HTTP::Get.new(uri) range_end = case @@ -309,5 +311,19 @@ def resource_type(io, key = "", content_type = "") end content_type_to_resource_type(content_type) end + + def find_blob_or_use_key(key) + if key.is_a?(ActiveStorage::BlobKey) + key + else + begin + blob = ActiveStorage::Blob.find_by(key: key) + blob ? ActiveStorage::BlobKey.new(blob.attributes.as_json) : key + rescue ActiveRecord::StatementInvalid => e + # Return the original key if an error occurs + key + end + end + end end end