Skip to content

Commit

Permalink
Handle case where url for proxied image does not contain a path
Browse files Browse the repository at this point in the history
  • Loading branch information
robbevp committed Feb 29, 2024
1 parent 2b9c9a8 commit dd82ebc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion app/models/proxied_image.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class ProxiedImage < ApplicationRecord
def process
Tempfile.create(encoding: 'ascii-8bit') do |file|
file.write fetch_image
filename = URI(url).path.split('/').last.split('.').first
filename = URI(url).path.split('/').last&.split('.')&.first || 'proxied-image'
content_type = Marcel::MimeType.for(file)
ext = Marcel::Magic.new(content_type).extensions.first
image.attach(io: file, filename: "#{filename}.#{ext}", content_type:)
Expand Down
15 changes: 15 additions & 0 deletions test/models/proxied_image_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,21 @@ class ProxiedImageTest < ActiveSupport::TestCase
end

assert_predicate proxy.image, :attached?
assert_equal 'image.jpg', proxy.image.filename.to_s
end

test 'should add default filename when url does not contain path' do
proxy = build(:proxied_image, url: 'https://example.com/?foo=bar')
stub_request(:any, 'https://example.com/?foo=bar')
.to_return(body: Rails.root.join('test/fixtures/files/image.jpg').read)

assert_difference ['ActiveStorage::Attachment.count', 'ActiveStorage::Blob.count'] do
# Automatically calls `.process` in `after_create_commit` callback
proxy.save!
end

assert_predicate proxy.image, :attached?
assert_equal 'proxied-image.jpg', proxy.image.filename.to_s
end

test 'should attach image without content type based on response' do
Expand Down

0 comments on commit dd82ebc

Please sign in to comment.