Raise a meaningful error if ActiveStorage::Current.host is blank

It's very hard to understand what happens with the following exception

  URI::InvalidURIError:
    bad URI(is not URI?): nil

that is raised when trying to generate a URL for Disk service without
setting the ActiveStorage::Current.host first.

This can happen when the ActiveStorage::SetCurrent is not included
in a controller, or when testing URL generation outside of the
controllers layer (eg. testing URL generation in a model).

Co-authored-by: elia <elia@schito.me>
Co-authored-by: filippo <dev@mailvore.com>
This commit is contained in:
Alberto Vena 2021-04-16 14:35:28 +02:00
parent 2af458a10d
commit f971a3f85d
No known key found for this signature in database
GPG Key ID: 525B72474A73BA6D
2 changed files with 14 additions and 0 deletions

@ -124,6 +124,10 @@ def generate_url(key, expires_in:, filename:, content_type:, disposition:)
purpose: :blob_key
)
if current_host.blank?
raise ArgumentError, "Cannot generate URL for #{filename} using Disk service, please set ActiveStorage::Current.host."
end
current_uri = URI.parse(current_host)
url_helpers.rails_disk_service_url(verified_key_with_expiration,

@ -23,6 +23,16 @@ class ActiveStorage::Service::DiskServiceTest < ActiveSupport::TestCase
end
end
test "URL generation without ActiveStorage::Current.host set" do
ActiveStorage::Current.host = nil
error = assert_raises ArgumentError do
@service.url(@key, expires_in: 5.minutes, disposition: :inline, filename: ActiveStorage::Filename.new("avatar.png"), content_type: "image/png")
end
assert_equal("Cannot generate URL for avatar.png using Disk service, please set ActiveStorage::Current.host.", error.message)
end
test "headers_for_direct_upload generation" do
assert_equal({ "Content-Type" => "application/json" }, @service.headers_for_direct_upload(@key, content_type: "application/json"))
end