@@ -17,9 +17,13 @@ module CloudinaryHelper
1717 alias cloudinary_url_internal_original cloudinary_url_internal
1818
1919 def cloudinary_url_internal ( source , options = { } )
20- if defined? ( ActiveStorage ::Blob . service . public_id ) && options . fetch ( :type , "" ) . to_s != "fetch"
21- source = ActiveStorage ::Blob . service . public_id ( source )
20+ service_instance , options = ActiveStorage ::Service ::CloudinaryService . fetch_service_instance_and_config ( source , options )
21+ service_instance ||= ActiveStorage ::Blob . service
22+
23+ if defined? ( service_instance . public_id ) && options . fetch ( :type , "" ) . to_s != "fetch"
24+ source = service_instance . public_id ( source )
2225 end
26+
2327 cloudinary_url_internal_original ( source , options )
2428 end
2529end
@@ -190,6 +194,33 @@ def public_id(key, filename = nil, content_type = '')
190194 full_public_id_internal ( public_id )
191195 end
192196
197+ def self . fetch_service_instance_and_config ( source , options )
198+ return [ nil , options ] unless defined? ( ActiveStorage ::BlobKey ) && source . is_a? ( ActiveStorage ::BlobKey ) &&
199+ source . respond_to? ( :attributes ) && source . attributes . key? ( :service_name )
200+
201+ service_name = source . attributes [ :service_name ]
202+
203+ begin
204+ service_instance = ActiveStorage ::Blob . services . fetch ( service_name . to_sym )
205+
206+ unless service_instance . instance_of? ( ActiveStorage ::Service ::CloudinaryService )
207+ Rails . logger . error "Expected service instance #{ service_instance . class . name } to be of type ActiveStorage::Service::CloudinaryService."
208+ return [ nil , options ]
209+ end
210+
211+ service_config = Rails . application . config . active_storage . service_configurations . fetch ( service_name )
212+ options = service_config . merge ( options )
213+ rescue NameError => e
214+ Rails . logger . error "Failed to retrieve the service instance for #{ service_name } : #{ e . message } "
215+ return [ nil , options ]
216+ rescue => e
217+ Rails . logger . error "An unexpected error occurred: #{ e . message } "
218+ return [ nil , options ]
219+ end
220+
221+ [ service_instance , options ]
222+ end
223+
193224 private
194225
195226 def api_uri ( action , options )
0 commit comments