Skip to content

Commit

Permalink
Fix asset type detection in ActiveStorage
Browse files Browse the repository at this point in the history
Fixes #555
  • Loading branch information
const-cloudinary committed Sep 8, 2024
1 parent de46088 commit 78ec967
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/active_storage/service/cloudinary_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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),
Expand All @@ -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 = {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

0 comments on commit 78ec967

Please sign in to comment.