From eebfaa417287b094d35ec65211b63207a970fb42 Mon Sep 17 00:00:00 2001 From: kibigo! Date: Wed, 27 Mar 2024 16:16:56 -0400 Subject: [PATCH] =?UTF-8?q?Fix=20=E2=80=9C::Collection=E2=80=9D=20definiti?= =?UTF-8?q?on=20with=20autoloading?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In autoloaded environments which reference `::Collection` in an initializer, `safe_constantize` will create a recursive autoloading loop. We can hook into `ActiveSupport::Dependencies` to check whether this is going to happen, and pre·emptively return `false` in that case (so that `::Collection` is defined properly), without changing behaviour where `::Collection` is getting `safe_constantize`d from somewhere else. --- app/models/collection.rb | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/app/models/collection.rb b/app/models/collection.rb index 7dfb86b3cd..e6a71805b0 100644 --- a/app/models/collection.rb +++ b/app/models/collection.rb @@ -2,4 +2,16 @@ # Provide plain collection model if not defined by the application. # Needed until Hyrax internals do not assume its existence. -class ::Collection < Hyrax.config.collection_class; end unless '::Collection'.safe_constantize +class ::Collection < Hyrax.config.collection_class; end unless ActiveSupport::Dependencies.then do |deps| + # In autoloading environments, when referencing +::Collection+ from the + # initializer, make sure that +safe_constantize+ wouldn’t just try loading + # this file again (which would produce a runtime error). Do this by manually + # searching for the file which should define +::Collection+ and checking if it + # is the one being currently loaded. + break true if Object.const_defined?(:Collection) + file_path = deps.search_for_file("collection") + expanded = File.expand_path(file_path) + expanded.delete_suffix!(".rb") + break false if deps.loading.include?(expanded) + '::Collection'.safe_constantize +end