@@ -711,11 +711,11 @@ def get_model_class(file)
711711 model_path = file . gsub ( /\. rb$/ , '' )
712712 model_dir . each { |dir | model_path = model_path . gsub ( /^#{ dir } / , '' ) . gsub ( /^\/ / , '' ) }
713713 begin
714- get_loaded_model ( model_path ) || raise ( BadModelFileError . new )
714+ get_loaded_model ( model_path , file ) || raise ( BadModelFileError . new )
715715 rescue LoadError
716716 # this is for non-rails projects, which don't get Rails auto-require magic
717717 file_path = File . expand_path ( file )
718- if File . file? ( file_path ) && silence_warnings { Kernel . require ( file_path ) }
718+ if File . file? ( file_path ) && Kernel . require ( file_path )
719719 retry
720720 elsif model_path =~ /\/ /
721721 model_path = model_path . split ( '/' ) [ 1 ..-1 ] . join ( '/' ) . to_s
@@ -726,8 +726,24 @@ def get_model_class(file)
726726 end
727727 end
728728
729+ # Retrieve loaded model class
730+ def get_loaded_model ( model_path , file )
731+ loaded_model_class = get_loaded_model_by_path ( model_path )
732+ return loaded_model_class if loaded_model_class
733+
734+ # We cannot get loaded model when `model_path` is loaded by Rails
735+ # auto_load/eager_load paths. Try all possible model paths one by one.
736+ absolute_file = File . expand_path ( file )
737+ model_paths =
738+ $LOAD_PATH. select { |path | absolute_file . include? ( path ) }
739+ . map { |path | absolute_file . sub ( path , '' ) . sub ( /\. rb$/ , '' ) . sub ( /^\/ / , '' ) }
740+ model_paths
741+ . map { |path | get_loaded_model_by_path ( path ) }
742+ . find { |loaded_model | !loaded_model . nil? }
743+ end
744+
729745 # Retrieve loaded model class by path to the file where it's supposed to be defined.
730- def get_loaded_model ( model_path )
746+ def get_loaded_model_by_path ( model_path )
731747 ActiveSupport ::Inflector . constantize ( ActiveSupport ::Inflector . camelize ( model_path ) )
732748 rescue StandardError , LoadError
733749 # Revert to the old way but it is not really robust
@@ -858,15 +874,6 @@ def classified_sort(cols)
858874 ( [ id ] << rest_cols << timestamps << associations ) . flatten . compact
859875 end
860876
861- # Ignore warnings for the duration of the block ()
862- def silence_warnings
863- old_verbose = $VERBOSE
864- $VERBOSE = nil
865- yield
866- ensure
867- $VERBOSE = old_verbose
868- end
869-
870877 private
871878
872879 def with_comments? ( klass , options )
0 commit comments