Files
openfoodnetwork/app/models/application_record.rb
Carlos Chitty b43fa55a7b Do not try to generate a URL for unpersisted blobs in development/test environment
Explicitly raise an error in `image_variant_url_for` if an Active Storage variant's blob is not persisted.

This addresses `ArgumentError`/`URI::InvalidURIError` in Rails 7.1, which occurs when attempting to generate a URL for an unsaved Active Storage blob. By raising, we ensure existing error handling in calling methods (e.g., `Spree::Image#url`) can provide graceful fallbacks (default image URLs).

This should only affect test and development environments where blobs may not be immediately persisted. Tests in `SuppliedProductImporter` have been updated to reflect this behavior.

References:
  - Suggestion: https://github.com/openfoodfoundation/openfoodnetwork/pull/13232#discussion_r2071116581
  - Example of failing test due to this: https://github.com/openfoodfoundation/openfoodnetwork/actions/runs/14739687958/job/41374346184?pr=13232
  - Related: https://github.com/rails/rails/issues/50234
2025-06-27 15:05:52 -04:00

35 lines
928 B
Ruby

# frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
include Spree::Core::Permalinks
include Spree::Preferences::Preferable
include Searchable
include ArelHelpers::ArelTable
include ArelHelpers::Aliases
include ArelHelpers::JoinAssociation
self.abstract_class = true
def self.image_service
ENV["S3_BUCKET"].present? ? :amazon_public : :local
end
# We might have a development environment without S3 but with a database
# dump pointing to S3 images. Accessing the service fails then.
def image_variant_url_for(variant)
if ENV["S3_BUCKET"].present? && variant.service.public?
variant.processed.url
else
unless variant.blob.persisted?
raise "ActiveStorage blob for variant is not persisted. Cannot generate URL."
end
url_for(variant)
end
end
def url_for(*args)
Rails.application.routes.url_helpers.url_for(*args)
end
end